How to vectorize these codes

Dear all,
these days i am dosing some modification on my code with vectorization. For the following codes:
function y=gam(a,m,n)
% cos(m*pi*x/a)*sin(n*pi*x/a)
if m==0
if n==m
y=0;
else
y=-a*(-1+(-1)^n)/(n*pi);
end
else
if n==m
y=0;
else
y=a*n*(-1+(-1)^(m+n))/(pi*(m^2-n^2));
end
end
I vectorlize it, but when m equal to n, the results is NAN. So please help me on vectorlizing it.
Thank you.
[Code formated, Jan - Please format your code in the future, thanks]

답변 (2개)

Jan
Jan 2012년 11월 5일
편집: Jan 2012년 11월 6일

1 개 추천

There is no loop and therefore it is not trivial to guess, which operation you want to be vectorized.
[EDITED] Now your problem got clear, thanks.
function y = gam(a,m,n)
y = zeros(size(m));
index = (m == 0 & n ~= m);
y(index) = -a*(-1+(-1).^n(index)) ./ (n(index)*pi);
index = (m ~= 0 & n ~= m);
y(index) = a.*n(index).*(-1+(-1).^(m(index)+n(index))) ./ ...
(pi*(m(index).^2 - n(index) .^ 2));
end
Not tested because I cannot run Matlab currently.
But this is a guess only. I cannot conclude what the vectorized version of "n == m" should be. Is it "ismember(n, m)" or "n == m" or "any(n == m, 2)" etc?

댓글 수: 1

Xianjie
Xianjie 2012년 11월 6일
m and n are matrix. So i want to vectorize this code.

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

Robert Cumming
Robert Cumming 2012년 11월 5일
편집: Robert Cumming 2012년 11월 5일

0 개 추천

help isnan

댓글 수: 4

Xianjie
Xianjie 2012년 11월 5일
편집: Xianjie 2012년 11월 5일
I just find this command. But is there some other method to vectorize these codes without NaN in the results?
function y=gam(a,m,n) % cos(m*pi*x/a)*sin(n*pi*x/a) if m==0 if n==m y=0; else y=-a*(-1+(-1)^n)/(n*pi); end else if n==m y=0; else y=a*n*(-1+(-1)^(m+n))/(pi*(m^2-n^2)); end end
I use this code to vectorize.
y = a*(~(m==n)).*((n.*(-1+(-1).^(m+n)))./(pi*(m.^2-n.^2)));
m and n also the matrix
Robert Cumming
Robert Cumming 2012년 11월 5일
its not vectorising thats the issue here - you have 0/0 when m=n => you get a NaN. use a logical check on the answer for isnan to covert it to a zero (as you indicated above).
Xianjie
Xianjie 2012년 11월 6일
Ok. Thank. Is there some other ways to solve this problem. Because if the dimension of matrix is large, the for loop will cost a lot of time. Thank you
m = [1 2 0 4 5];
n = [3 3 0 3 3];
y = m./n
y(isnan(y)) = 0
No for loop required - as I said use logical indexing and isnan.

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

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2012년 11월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by