Create a sequence based on other arrays

1 回表示 (過去 30 日間)
luca
luca 2019 年 10 月 3 日
コメント済み: Nipun Katyal 2020 年 3 月 2 日
Given the arrays
SP = [1 2 4 6 7 9 10]
V = [5 20 10 15 5 20 10 ]
I want to create a random array P that contain the elements of SP repeated as many times as is indicated in V. So the element one has to be repeated 5 times, two repeated 20 times, four repeated 10 times and so on.
An important rule to respect is that at maximum we can mix two elements at time, respecting the order indicated in V. So the first elements in the random sequence will be 1 and 2, 4 can appear just when one between 1 and 2 will be terminated.
Let's see an example:
P = [1 1 2 1 2 1 2 2 1 2 2 4 2 4 2 4 2 4 4 2 2 4 2 2 4 4 2 2 4 4 2 6 2 6 2 6 6 2 6 2 6 6 7 6 7 7 6 6 7 6 6 7 6 9 6 9 6 9 9 10 10 9 9 10 9 9 10 9 9 10 9 9 10 9 9 10 9 9 10 10 9 9 10 9 9]
As we can see as soon as 1 has been repeated 10 times, then 4 appears in the sequence in combination with 2. Then again is 4 that terminated before 2 and 6 enters in the sequence with 2.
May someone help me with this task?

回答 (1 件)

Nipun Katyal
Nipun Katyal 2020 年 3 月 2 日
You can do this by maintaining two variables to store the current two indices until the correponding elements in V are exhausted, I hope this helps.
  2 件のコメント
Guillaume
Guillaume 2020 年 3 月 2 日
if(idx <= maxElem && idx< maxElem)
I suspect that the second idx is meant to be idy. Otherwise it doesn't make much sense, the second is always true if the first half is.
Note that in matlab you don't need to enclose if expressions in ().
Nipun Katyal
Nipun Katyal 2020 年 3 月 2 日
Yes it is supposed to be idy

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

カテゴリ

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

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by