How to vectorize this condition switch code
조회 수: 6 (최근 30일)
이전 댓글 표시
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
답변 (2개)
Dr. Seis
2012년 11월 12일
편집: Dr. Seis
2012년 11월 12일
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
Jan
2012년 11월 12일
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
Dr. Seis
2012년 11월 12일
편집: Dr. Seis
2012년 11월 12일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!