Asked by John
on 12 Jan 2015

I'm trying unsuccessfully to substitute a number for NaN in anonymous function. Here it's an example of the problem. Bear with it's silliness please:

clc;

clear all;

f=@(x) x*1/x;

g=@(x) (~isnan(f(x))).*f(x) + (isnan(f(x))).*1;

I'd expect that g(0)=1, but it's still NaN. What is wrong in the way that I defined g?

Answer by Alfonso Nieto-Castanon
on 13 Jan 2015

Edited by Alfonso Nieto-Castanon
on 13 Jan 2015

Accepted Answer

There may be "cleaner" ways to do this but one possibility would be:

g = @(x) [f(x) 1]*sparse(1+isnan(f(x)),1,1,2,1);

EDIT: and as others have pointed out the problem with your original g function is that, when f(x) is NaN, you get 0*NaN + 1*1 which still evaluates to NaN...

Sign in to comment.

Answer by John Petersen
on 13 Jan 2015

You have .*f(x) in g(x), which is still giving you a NaN

Sign in to comment.

Answer by Star Strider
on 13 Jan 2015

If you want to define L’Hospital’s rule, you have to define it specifically. In the IEEE standard that MATLAB implements, 0/0 is NaN.

See if this works in your application:

n = @(x) 2.*x; % Numerator Function

d = @(x) x; % Denominator Function

Lh = @(n,d,x) (n(x+1E-12)-n(x)) ./ (d((x+1E-12)-d(x))); % L’Hospital’s RUle

Lh0 = Lh(n,d,0) % Evaluating AT 0

Lh2 = Lh(n,d,2) % Evalutaing At 2

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 2 Comments

## John (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/169709-substituting-a-number-for-nan-in-anonymous-function#comment_260409

## Guillaume (view profile)

## Direct link to this comment

https://it.mathworks.com/matlabcentral/answers/169709-substituting-a-number-for-nan-in-anonymous-function#comment_260418

Sign in to comment.