efficient way of transforming vector

1 view (last 30 days)
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!
  2 Comments
Jos (10584)
Jos (10584) on 16 Jul 2013
Just for your information, this is an example of run-length decoding. There are very efficient contributions available on the Matlab File Exchange for encoding and decoding run lengths (see, e.g., RUDE).
the cyclist
the cyclist on 16 Jul 2013
@Jos, good comment. My first thought on seeing this question is that I was pretty sure that it was covered in the classic "tips and tricks" document of Peter Acklam (still available on the web here: http://home.online.no/~pjacklam/matlab/doc/mtt/doc/mtt.pdf).
I was correct in my memory, but it turned out that the three algorithms he offers do not correctly handle cases where there is a zero run-length.

Sign in to comment.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 16 Jul 2013
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)

More Answers (2)

Azzi Abdelmalek
Azzi Abdelmalek on 16 Jul 2013
Edited: Azzi Abdelmalek on 16 Jul 2013
B=cell2mat(arrayfun(@(x) x*ones(A(x),1),1:numel(A),'un',0)')
%or a for loop which is much faster
B=[]
for k=1:numel(A)
B(end+1:end+A(k),1)=k*ones(A(k),1)
end

Lokesh Ravindranathan
Lokesh Ravindranathan on 16 Jul 2013
b is the resultant vector
b = [];
j = 1;
for i = 1:numel(a)
b(j: j + a(i) - 1) = i;
j = j+ a(i);
end

Categories

Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!