will_cheuk
will_cheuk

Reputation: 379

How to fix nan in anonymous function?

Suppose I have a function f(x) defined, which gives nan when it is very large, say x>100. Fortunately, when x>100, I can replace f by another function g. So I would like to define:

h = @(x)isnan(f(x)).*f(x)+isnan(f(x)).*g(x)

However, when I substitute h(1001), it gives nan. Is it possible to define h so that it gives g(1001) instead of nan? The only restriction is that I need to have anonymous function h for later use, say I would like to use it in integration, i.e., integral(h,0,inf).

Example: Suppose I have a function:

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

This function is very easy and must be 1. I construct a function:

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

How to make g to be well defined so that I can still evaluate integral(g,-1,1)? For this example, I know I can evaluate it easily, but my restriction is that I need to define anonymous function g and use integral to do it.

Upvotes: 2

Views: 274

Answers (2)

AVK
AVK

Reputation: 2149

There is a solution without any additional functions:

f = @(x)x.*1./x;
g = @(x)100+x;
h= @(x)getfield(struct('a',f(x),'b',g(x)),char(isnan(f(x))+'a'))

Upvotes: 0

Jonathan Olson
Jonathan Olson

Reputation: 1186

You would need to make a regular function and wrap it with the anonymous function.

i.e.

function r = ternary(a, b, c)
  if (a)
    r = b;
  else
    r = c;
  end
end

h = @(x)ternary(isnan(f(x)), g(x), f(x));

Note that this will evaluate your function twice. A less generalized solution for your particular case that won't evaluate the function twice.

function r = avoidNAN(a, b)
  if (isnan(a))
    r = b;
  else
    r = a;
  end
end

Upvotes: 1

Related Questions