yankeefan11
yankeefan11

Reputation: 485

Creating piecewise anonymous function matlab

I have an expression that I want to be 0 if the sum of the two variables is even, and a function if the sum is odd. I tried this:

fmn = @(m,n) (mod(m+n,2)~=0)*16*m*n/(pi^2*(m^2-n^2)^2);

My issue is that if I do this for m=n, then I get NaN instead of 0. How can I resolve this to give 0 foro something like that?

Upvotes: 1

Views: 231

Answers (1)

TroyHaskin
TroyHaskin

Reputation: 8401

The 1/(m^2-n^2) is generating the NaN which is corrupting your function. To get around this, you can add a small finiteness to the denominator (i.e., machine epsilon):

fmn = @(m,n) (mod(m+n,2)~=0)*16*m*n/(pi^2*((m^2-n^2)^2 + eps()));

or have a term that is only non-zero when m and n are sufficiently close:

fmn = @(m,n) (mod(m+n,2)~=0)*16*m*n/(pi^2*((m^2-n^2)^2 + abs(m-n)<=eps(m)));

Upvotes: 4

Related Questions