How to vectorize this condition switch code
6 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
4 Kommentare
Antworten (2)
Dr. Seis
am 12 Nov. 2012
Bearbeitet: Dr. Seis
am 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.
0 Kommentare
Jan
am 12 Nov. 2012
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.
2 Kommentare
Dr. Seis
am 12 Nov. 2012
Bearbeitet: Dr. Seis
am 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
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!