Please help me in inserting ones in a given matrix in special rows

1 view (last 30 days)
Suppose if I already have a matrix 'X' having only one '1' in few rows and other rows contains zeros only for example matrix given below
X =
[0 0 0 0 1 0 0 0 0 0;
0 1 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
i need a matrix having few (specified number) '1's after existing '1' in each row.
for example output matrix is
Y =
[0 0 0 0 1 1 1 1 0 0;
0 1 1 1 1 1 0 0 0 0;
0 0 1 1 1 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
number of ones to be inserted in specified rows are D = [4; 5; 3; 2; 4];
as in example matrix last two rows are zeros only, there is no need to insert ones in those rows,as there is no '1' appearing in those rows

Answers (2)

Stephen23
Stephen23 on 6 Jul 2016
Edited: Stephen23 on 6 Jul 2016
MATLAB is a high-level language, so there is no need to waste time with ugly loops as if this was some poor low-level language like C++. Vectorized code is much neater:
>> tmp = cumsum(cumsum(X,2),2);
>> Y = bsxfun(@le,tmp,D) & tmp
Y =
0 0 0 0 1 1 1 1 0 0
0 1 1 1 1 1 0 0 0 0
0 0 1 1 1 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

José-Luis
José-Luis on 6 Jul 2016
X = [0 0 0 0 1 0 0 0 0 0;
0 1 0 0 0 0 0 0 0 0;
0 0 1 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0 0]
D = [4; 5; 3; 2; 4];
for row = 1:numel(D)
ic = find(X(row,:));
if ~isempty(ic)
X(row,ic:ic+D-1)= 1;
end
end

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!