Adding values to a vector
조회 수: 3 (최근 30일)
이전 댓글 표시
Dear Matlab forum, I have a vector, T for which I would like to add values to certain indices in a loop. My simplified code is:
T=zeros(10,1)
for iter=1:100
r=[some indices]; % the indices change each loop and are somewhat random
E=[some values for the indices]; % length(E)==length(r)
T(r)=T(r)+E;
end
The issue I am having is that r may contain a multiple occurrences of given index within a single iteration, for example r=[1 4 2 4], and E could be=[2 2 2 2]. I would like to add BOTH values of E to the index 4, but my above code only adds the last one and ignores the first. What is the most efficient way to solve this issue? Thank you very much, -Eli
댓글 수: 0
채택된 답변
Matt Fig
2011년 6월 30일
It has to be done in a loop? You could put a nested loop in there and loop over r...
%
%
EDIT
Here is one way to do it.
T = 1:5;
r = [1 1 1 3 4];
E = [3 3 2 2 5];
T = T + accumarray(r.',E.',[5 1]).'
But it might be slower than using a loop... In fact, since you say that T is 20,000 times longer than r, I would bet this was slower than a loop.
%
%
%
%
EDIT2 The timings report...
Have a look for yourself. Of course some of the accumarray solution could be sped of if the r and E could be made column vectors, which would avoid the transposition, but I doubt that will be much faster...
function [] = accum_loop
T = 1:2e7;
rand('twister',33)
tic
for ii = 1:100
r = ceil(rand(1,1000)*2e7);
E = ceil(rand(1,1000)*10);
for jj = 1:length(r)
T(r(jj)) = T(r(jj)) + E(jj);
end
end
toc
T2 = 1:2e7;
rand('twister',33)
tic
for ii = 1:100
r = ceil(rand(1,1000)*2e7);
E = ceil(rand(1,1000)*10);
T2 = T2 + accumarray(r.',E.',[2e7 1]).' ;
% T2 = T2 + accumarray(r.',E.',[2e7 1],@sum,0,true).' ;
end
toc
isequal(T,T2)
I get, as it stands:
Elapsed time is 0.016339 seconds.
Elapsed time is 7.278608 seconds.
And with your modifications (function handles are slow!):
Elapsed time is 0.016107 seconds.
Elapsed time is 23.642409 seconds.
댓글 수: 13
Matt Fig
2011년 7월 1일
You're welcome. In the future you should use the profiler to see where the bottleneck in your code is hiding.
help profile
This is an invaluable tool for helping speed up slow code.
추가 답변 (1개)
Jan
2011년 7월 1일
Try to use a LOGICAL vector for r, which has 2 advantages:
- The vector needs less memory such that the allocation is faster
- LOGICAL indices do not need a boundary check for each element, such that the copy is faster. The index is applied twice in "T(r)=T(r)+E;"
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!