I'm looking to eliminate the following for loop:
조회 수: 4 (최근 30일)
이전 댓글 표시
I'm looking to eliminate the following for loop:
for j=1:96
rn(ijk(j))=rn(ijk(j))+mp(j);
end
Background: rn is a 200x3x3 matrix, ijk is a 1800x1 matrix and np is a 12x8 matrix. ijk describes the mapping between mp and (the much larger) rn. For example, when j=1, mp(j)=0.84 and ijk(1)=601. This loop is embedded in a much larger loop.
There has got to be a way to eliminate the for loop presented here. Any suggestions?
댓글 수: 0
채택된 답변
Sean de Wolski
2012년 1월 13일
Perhaps:
idx = 1:96;
rn(ijk(idx))=rn(ijk(idx))+mp(idx);
댓글 수: 3
Alex
2012년 1월 13일
I just played around with a similar setup and I'm getting the same answer using either method.
One way that it could be causing different answers is if the data types are different (ex. doubles vs cells).
You can further debug this to see what is going on by reducing the problem. Start with a smaller idx (even 1) to see if you are getting the same results both ways. If 1 works, make idx bigger until you find the problem.
Sean de Wolski
2012년 1월 13일
Could you try each method in its entirety in two different functions and then compare the results after? Perhaps you're performing the same operation twice or not preallocating the matrices the same way (i.e. different sized results)
추가 답변 (2개)
Sean de Wolski
2012년 1월 18일
%Data:
mp=[0.1;0.2;0.3];
ijk=[1,2,1];
rnsz = [4 1]; %the size you want rn to be:
%Engine:
rn = accumarray(ijk',mp',rnsz); % Build rn; note transpose of subs/vals
참고 항목
카테고리
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!