필터 지우기
필터 지우기

How to vectorize this condition switch code

조회 수: 5 (최근 30일)
Xianjie
Xianjie 2012년 11월 6일
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
Harshvardhan
Harshvardhan 2012년 11월 6일
where is n?
Xianjie
Xianjie 2012년 11월 6일
Sorry. Now in these codes, there is no n. Only want to vectorize this code and also it can fit for n and n1.

댓글을 달려면 로그인하십시오.

답변 (2개)

Dr. Seis
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.

Jan
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
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
Jan
Jan 2012년 11월 12일
@Elige: Thanks. I loose the overview in this stack of threads.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by