create a specific matrix data ?

1 view (last 30 days)
MUKESH KUMAR
MUKESH KUMAR on 3 Jan 2018
Edited: Guillaume on 3 Jan 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???

Accepted Answer

Guillaume
Guillaume on 3 Jan 2018
Edited: Guillaume on 3 Jan 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

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!