Azzera filtri
Azzera filtri

How to vectorize a for-loop please help?

1 visualizzazione (ultimi 30 giorni)
Erin Pratt
Erin Pratt il 18 Giu 2021
Commentato: dpb il 18 Giu 2021
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 Commento
dpb
dpb il 18 Giu 2021
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...

Accedi per commentare.

Risposte (0)

Prodotti


Release

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by