How to vectorize this condition switch code

3 ビュー (過去 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 Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by