Create a sequence based on other arrays
1 次查看(过去 30 天)
显示 更早的评论
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?
0 个评论
回答(1 个)
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
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 ().
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!