Replicate values in a matrix i-1 times

1 回表示 (過去 30 日間)
Nicole McEwan
Nicole McEwan 2020 年 3 月 3 日
コメント済み: Fabio Freschi 2020 年 3 月 3 日
I want to create a new array that duplicates the first value of A, then the rest of the values (i-1) times. For example,
A=[1; 4; 8; 3; 2; 6]
I want
B=[1; 4; 8; 8; 3; 3; 3; 2; 2; 2; 2; 6; 6; 6; 6; 6]
My first attempt was a for loop but I couldn't make it work. My other idea is to do C=repmat(A,1,6) and then pull out B=[C(1,1); C(2,1); C(3,1); C(3,2); ..... etc] but I don't know how to automate this, since my actual A has 2000 values.
Any help is appreciated! Thanks.

回答 (2 件)

David Hill
David Hill 2020 年 3 月 3 日
B=repelem(A,[1,1:5]);
  1 件のコメント
Fabio Freschi
Fabio Freschi 2020 年 3 月 3 日
Nice!

サインインしてコメントする。


Fabio Freschi
Fabio Freschi 2020 年 3 月 3 日
Quick and dirty for loop
A=[1; 4; 8; 3; 2; 6]
B = [];
for i = 1:length(A)
B = [B; repmat(A(i),i,1)];
end
You can also play a bit to allocate correctly B outside the loop. It's a nice exercise

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by