Create vector with predetermined number of certain elements
15 ビュー (過去 30 日間)
古いコメントを表示
Hi everyone,
I have a problem where I have a set of numbers, eg; [3 5 9] and for each of these numbers an amount of occurences eg. [2 1 5]. Now i would like to create a vector containing these numbers the prespecified amount of times, so for the example the result would be [3 3 5 9 9 9 9 9 ]. Is there an elegant way to do this in MATLAB, that is, vectorized?
Thanks in advance for your input.
0 件のコメント
採用された回答
Star Strider
2016 年 3 月 27 日
Use the repelem funciton:
V = [3 5 9];
N = [2 1 5];
Out = repelem(V, N)
Out =
3 3 5 9 9 9 9 9
2 件のコメント
その他の回答 (1 件)
Image Analyst
2016 年 3 月 27 日
Here's one straightforward, easy-to-understand way that's pretty fast.
numbers = [3 5 9];
occurrences = [2 1 5];
output = zeros(1, sum(occurrences));
index1 = 1;
for k = 1 : length(numbers)
index2 = index1 + occurrences(k) - 1;
output(index1:index2) = numbers(k)
index1 = index2 + 1;
end
参考
カテゴリ
Help Center および File Exchange で Performance and Memory についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!