efficient way of transforming vector

2 visualizaciones (últimos 30 días)
Rien
Rien el 16 de Jul. de 2013
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 comentarios
Jos (10584)
Jos (10584) el 16 de Jul. de 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 el 16 de Jul. de 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.

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 16 de Jul. de 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)

Más respuestas (2)

Azzi Abdelmalek
Azzi Abdelmalek el 16 de Jul. de 2013
Editada: Azzi Abdelmalek el 16 de Jul. de 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 el 16 de Jul. de 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

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by