efficient way of transforming vector

1 次查看(过去 30 天)
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 个评论
Jos (10584)
Jos (10584) 2013-7-16
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 2013-7-16
@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.

请先登录,再进行评论。

采纳的回答

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

更多回答(2 个)

Azzi Abdelmalek
Azzi Abdelmalek 2013-7-16
编辑:Azzi Abdelmalek 2013-7-16
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
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

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by