repeating an index number n times in a vector

Hi People,
I'd like to transform a vector p like this one. p=[3 0 2 2 1 0 3]
Into a new vector that has n times the indexnumber of n, for example:
new vector: v=[1 1 1 3 3 4 4 5 7 7 7] so it has 3 times 1, zero times 2, 2 times 3 and so on.
the numbers generated in p are variable but are always between 0 and 15
I hope you can help me.
Regards, Siem

 採用された回答

Amit
Amit 2014 年 1 月 23 日

0 投票

v = [];
count = 1;
for j = 1:length(p)
if p(j) ~= 0
v(count:count+p(j)-1) = j*ones(p(j),1);
count = count + p(j);
end
end

1 件のコメント

Siem Nijskens
Siem Nijskens 2014 年 1 月 23 日
Hi Amit,
Thank you so much this has been driving me crazy but your solution works perfectly.
Regards, Siem

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

その他の回答 (1 件)

Chris
Chris 2014 年 1 月 23 日

0 投票

Hey Siem,
I would do it like this:
v = p .* 1:length(p);

1 件のコメント

Siem Nijskens
Siem Nijskens 2014 年 1 月 23 日
Hi Cris,
Thanks for answering my question, unfortunately your solution didn't work.
Regards, Siem

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

カテゴリ

質問済み:

2014 年 1 月 23 日

コメント済み:

2014 年 1 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by