How to vectorize this condition switch code
5 views (last 30 days)
Show older comments
I have one code like this
function y = intefai1(a,m1,m)
if m1 >= 0
if m >= 0
y = alpha1(a,m1,m);
y = -gam(a,m1,abs(m));
if m >= 0
y = -gam(a,m,abs(m1));
y = betass(a,abs(m),abs(m1));
How can i avoid for loop with logical operation? Thanks
Dr. Seis on 12 Nov 2012
Edited: Dr. Seis on 12 Nov 2012
From your more recent question, I found:
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.
Does the method work, which I have provided in your former thread http://www.mathworks.com/matlabcentral/answers/52831-how-to-vectorize-these-codes ? An equivalent approach should work here also.
Find more on Solver Outputs and Iterative Display in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!