create a specific matrix data ?

1 visualización (últimos 30 días)
MUKESH KUMAR
MUKESH KUMAR el 3 de En. de 2018
Editada: Guillaume el 3 de En. de 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???

Respuesta aceptada

Guillaume
Guillaume el 3 de En. de 2018
Editada: Guillaume el 3 de En. de 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

Más respuestas (0)

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by