How to vectorize a for-loop please help?
조회 수: 3 (최근 30일)
이전 댓글 표시
I am trying to eliminate a for-loop that looks like:
for k=1:N
Smat1(i,j)=Smat1(i,j)+Sloctemp(k,1,1)*(Sloc(k,1,5)==countrow && Sloc(k,5,1)==countcol)*(mod(j,2)==1 && mod(i,2)==1);
end
the i and j are for loops that this is nested in.
My attempt to eliminate the k loop is:
kk=1:N;
Smat1(i,j)=Smat1(i,j)+Sloctemp(kk,1,1).*(Sloc(kk,1,5)==countrow && Sloc(kk,5,1)==countcol).*(mod(j,2)==1 && mod(i,2)==1);
But the error that I get is "Operands to the || and && operators must be convertable to ligical scalar values."
Can I please get help on my syntax? I am attempting this vectorization because this part of the code is looped many millions of times to achieve the overal project objective.
Thanks!
Erin
댓글 수: 1
dpb
2021년 6월 18일
Formatted code above --dpb
Your short-circuit operators would have to be "&" instead, but you've introduced length issues that will pop up when you make just that change.
kk is a vector so the variables addressed with it are vectors and you're trying to store a vector into a single array location on the LHS
It's certainly not at all clear what the point of this is, but at a minimum you'd have to have something like
kk=1:N;
Smat1(kk,j)=Smat1(kk,j)+Sloctemp(kk,1,1).*(Sloc(kk,1,5)==countrow && Sloc(kk,5,1)==countcol).*(mod(j,2)==1 && mod(i,2)==1);
but then there's a length mismatch in the last term with the mod() expressions as they're still one element in length.
Believe it would be better to outline the overall problem trying to be solved and let somebody see the big picture instead of trying peephole optimization...
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!