Adding values to a vector
Show older comments
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
Accepted Answer
More Answers (1)
Jan
on 1 Jul 2011
1 vote
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;"
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!