Filter löschen
Filter löschen

efficient way of transforming vector

1 Ansicht (letzte 30 Tage)
Rien
Rien am 16 Jul. 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 Kommentare
Jos (10584)
Jos (10584) am 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 am 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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 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)

Weitere Antworten (2)

Azzi Abdelmalek
Azzi Abdelmalek am 16 Jul. 2013
Bearbeitet: Azzi Abdelmalek am 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 am 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

Kategorien

Mehr zu Characters and Strings finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by