Please help me in inserting ones in a given matrix in special rows
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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
Antworten (2)
Stephen23
am 6 Jul. 2016
Bearbeitet: Stephen23
am 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
0 Kommentare
José-Luis
am 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
0 Kommentare
Siehe auch
Kategorien
Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!