This can be done by combining ismember and cumsum:
d1(cumsum(ismember(1:sum(howMany1),cumsum([1 howMany1]))))
Breakdown:
Compare 1:sum(howMany1)
with the cumulative sum of howMany1
. This is a vector with 1 and 0 that shows the position of where the next value from d1 should start.
ismember(1:sum(howMany1),cumsum([1 howMany1]))
ans =
1 0 0 1 0 1 0 1 1 0
The cumulative sum of this gives a vector that looks like:
cumsum(ismember(1:sum(howMany1),cumsum([1 howMany1])))
ans =
1 1 1 2 2 3 3 4 5 5
Now, this can be used as indices to d1
when creating the d1_repeated.
d1(cumsum(ismember(1:sum(howMany1),cumsum([1 howMany1]))))
ans =
1 1 1 2 2 1 1 3 4 4