Effacer les filtres
Effacer les filtres

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

1 vue (au cours des 30 derniers jours)
MANISH KUMAR
MANISH KUMAR le 6 Juil 2016
Commenté : Stephen23 le 6 Juil 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
  2 commentaires
José-Luis
José-Luis le 6 Juil 2016
Modifié(e) : José-Luis le 6 Juil 2016
Where would you insert the ones if a row is only zeros?

Connectez-vous pour commenter.

Réponses (2)

Stephen23
Stephen23 le 6 Juil 2016
Modifié(e) : Stephen23 le 6 Juil 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 le 6 Juil 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

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by