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)
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
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
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)
댓글 수: 0
추가 답변 (2개)
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
댓글 수: 0
Lokesh Ravindranathan
2013년 7월 16일
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!