Element-wise array replication according to a count [duplicate]
Solution 1:
Here's one way I like to accomplish this:
>> index = zeros(1,sum(rep));
>> index(cumsum([1 rep(1:end-1)])) = 1;
index =
1 0 1 0 0 1 1 0 0 0 0
>> index = cumsum(index)
index =
1 1 2 2 2 3 4 4 4 4 4
>> vv = v(index)
vv =
3 3 1 1 1 9 4 4 4 4 4
This works by first creating an index vector of zeroes the same length as the final count of all the values. By performing a cumulative sum of the rep
vector with the last element removed and a 1 placed at the start, I get a vector of indices into index
showing where the groups of replicated values will begin. These points are marked with ones. When a cumulative sum is performed on index
, I get a final index vector that I can use to index into v
to create the vector of heterogeneously-replicated values.
Solution 2:
To add to the list of possible solutions, consider this one:
vv = cellfun(@(a,b)repmat(a,1,b), num2cell(v), num2cell(rep), 'UniformOutput',0);
vv = [vv{:}];
This is much slower than the one by gnovice..