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

1 visualización (últimos 30 días)
MANISH KUMAR
MANISH KUMAR el 6 de Jul. de 2016
Comentada: Stephen23 el 6 de Jul. de 2016
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

Respuestas (2)

Stephen23
Stephen23 el 6 de Jul. de 2016
Editada: Stephen23 el 6 de Jul. de 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 el 6 de Jul. de 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

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by