Asked by Xianjie
on 6 Nov 2012

Dear all,

I have one code like this

function y = intefai1(a,m1,m)

% fai(m1,x)*fai(m,x)

if m1 >= 0

if m >= 0

y = alpha1(a,m1,m);

else

y = -gam(a,m1,abs(m));

end

else

if m >= 0

y = -gam(a,m,abs(m1));

else

y = betass(a,abs(m),abs(m1));

end

end

How can i avoid for loop with logical operation? Thanks

Answer by Dr. Seis
on 12 Nov 2012

Edited by Dr. Seis
on 12 Nov 2012

From your more recent question, I found:

M=10;N=10;P=4;

for m1=-P:M

for n1=-P:N

s=(m1+P)*(N+1+P)+n1+P+1;

for m=-P:M

for n=-P:N

t=(m+P)*(N+1+P)+n+P+1;

A2(s,t)=intefai1(a,m1,m);

end

end

end

end

I am still not sure what a is (so I will assume it is a constant like your m1 and m). So instead of those for loops you could just:

[m,m1]=meshgrid(-P:M); % m and m1 are now matrices !!

A2 = zeros(size(m));

A2(m1 >= 0 & m >= 0) = ...

alpha( a, m1(m1 >= 0 & m >= 0), m(m1 >= 0 & m >= 0) );

And similarly for the other conditions.

Now... I realize that this produces a (P+M+1)x(P+M+1) matrix instead of a ((P+M+1)*(P+N+1))x((P+M+1)*(P+N+1)) matrix. Once you have these values for the smaller matrix you can populate the larger matrix by essentially copying/replicating... you don't want to have to do the same computations (P+M+1)*(P+N+1) times if you only need to do it once and then just replicate.

Sign in to comment.

Answer by Jan
on 12 Nov 2012

Dr. Seis
on 12 Nov 2012

I guess the bigger issue might have been how to construct m and m1 (or m and n in your case) such that the logical indexing scheme would produce the same result as the multi-for-loop-if-else configuration.

The information above I took from their more recent question here: http://www.mathworks.com/matlabcentral/answers/53399-this-calculate-error-is-why

Jan
on 12 Nov 2012

@Elige: Thanks. I loose the overview in this stack of threads.

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 4 Comments

## Matt J (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/52968-how-to-vectorize-this-condition-switch-code#comment_109652

## Xianjie (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/52968-how-to-vectorize-this-condition-switch-code#comment_109719

## Harshvardhan (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/52968-how-to-vectorize-this-condition-switch-code#comment_109721

## Xianjie (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/52968-how-to-vectorize-this-condition-switch-code#comment_109740

Sign in to comment.