Create vector with predetermined number of certain elements

조회 수: 15 (최근 30일)
Bartdp
Bartdp 2016년 3월 27일
댓글: Star Strider 2016년 3월 27일
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.

채택된 답변

Star Strider
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
Bartdp
Bartdp 2016년 3월 27일
편집: Bartdp 2016년 3월 27일
Perfect ;), thanks for your answer.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
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
  댓글 수: 1
Bartdp
Bartdp 2016년 3월 27일
편집: Bartdp 2016년 3월 27일
Thanks for your answer. I need to create such a vector several times within the body of a loop, and therefore making a lot of them. Do you have any idea on how to vectorize this code? Thanks in advance

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by