Q:
Suppose I have a vector like: v = [ 3 2 4 1 3 2...]
I want to obtain a new vector like: w = [3 3 3 2 2 4 4 4 4 1 3 3 3 2 2...]
basically every value repeates it's own number of times.
A1 (one-liner):
w = cell2mat(arrayfun(@(x) x+zeros(1,x), v, 'uni', 0))A2:
v(v == 0) = [] % Need to get rid of zeros in the general case.Speed test:
c = cumsum(v)
w = zeros(1,c(end))
w([1,c(1:end-1)+1]) = 1
w = v(cumsum(w))
% v = randi(800,1,90000)+1;
Method 1:
Elapsed
time is 1.997060 seconds.
Method 2:
Elapsed time is 1.630775 seconds.
Two methods are about same speed.
No comments:
Post a Comment