MATLAB: Efficient way of transforming vector

vector manipulation

Hi,
I have a rather simple question on vector manipulation. I want to do some matrix manipulation as efficiently as possible and I think I found a solution, but therefore I have to do some vector manipulation. For example, I want to transform vector A into vector B:
A =
2
1
0
3
B =
1
1
2
4
4
4
So each element of A shows how many times the number 1,2,3,4… should be repeated. Is there a way to do this transformation in an efficient way without setting up a loop myself?
Thanks for your answer!

Best Answer

A =[2
1
0
3];
n = A ~= 0;
k = cumsum(A);
k1 = k(n);
s = (1:numel(A))';
s1 = s(n);
k2 = k1 - A(n) + 1;
ii = zeros(k(end),1);
ii(k2) = 1;
idx = cumsum(ii);
out = s1(idx)