create a specific matrix data ?

1 visualizzazione (ultimi 30 giorni)
MUKESH KUMAR
MUKESH KUMAR il 3 Gen 2018
Modificato: Guillaume il 3 Gen 2018
I have a matrix N=[2;3;4;2;4;1;4;3;2;1] (10*1 size) then from this i want to create a matrix like this that
for i=1:10
M(i)= i*ones(N(i),1)
end
I want this matrix M=[1;1;2;2;2;3;3;3;3;4;4;5;5;5;5;6;7;7;7;7;8;8;8;9;9;10]; but I did not get this???

Risposta accettata

Guillaume
Guillaume il 3 Gen 2018
Modificato: Guillaume il 3 Gen 2018
The desired result is trivially obtained with repelem:
N=[2;3;4;2;4;1;4;3;2;1];
M = repelem((1:numel(N))', N)
If you were to use a loop to generate M, the most efficient way would probably be:
startidx = cumsum([1; N]);
M = zeros(sum(N), 1);
for idx = 1:numel(N)
M(startidx(idx) : startidx(idx)+N(idx)-1) = idx;
end

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by