Adding values to a vector
이전 댓글 표시
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
채택된 답변
추가 답변 (1개)
Jan
2011년 7월 1일
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;"
카테고리
도움말 센터 및 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!