My question is similar to this one, but I would like to replicate each element according to a count specified in a second array of the same size.
An example of this, say I had an array v = [3 1 9 4], I want to use rep = [2 3 1 5] to replicate the first element 2 times, the second three times, and so on to get [3 3 1 1 1 9 4 4 4 4 4].
So far I’m using a simple loop to get the job done. This is what I started with:
vv = [];
for i=1:numel(v)
vv = [vv repmat(v(i),1,rep(i))];
end
I managed to improve by preallocating space:
vv = zeros(1,sum(rep));
c = cumsum([1 rep]);
for i=1:numel(v)
vv(c(i):c(i)+rep(i)-1) = repmat(v(i),1,rep(i));
end
However I still feel there has to be a more clever way to do this… Thanks
Here’s one way I like to accomplish this:
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
repvector with the last element removed and a 1 placed at the start, I get a vector of indices intoindexshowing where the groups of replicated values will begin. These points are marked with ones. When a cumulative sum is performed onindex, I get a final index vector that I can use to index intovto create the vector of heterogeneously-replicated values.