create a specific matrix data ?

1 次查看(过去 30 天)
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???

采纳的回答

Guillaume
Guillaume 2018-1-3
编辑:Guillaume 2018-1-3
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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by