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!