create a specific matrix data ?

1 回表示 (過去 30 日間)
MUKESH KUMAR
MUKESH KUMAR 2018 年 1 月 3 日
編集済み: Guillaume 2018 年 1 月 3 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by