How to write piecewise function using anonymous function in Matlab?

1.3k Views Asked by At

I would like to code the following function:

$$f(x)=\begin{cases} \dfrac{\sin(x)}{x} & x\neq 0 \\ 1 & x = 0. \end{cases} $$

I am doing the following:

f = @(x) (sin(x)./x.*(x~=0) + 1.*(x==0));

However, f(0)returns NaN, while it must return 1.

Do you see what I am missing? Thanks

2

There are 2 best solutions below

1
On

The problem is that $\sin(0)./0$ is NaN, and multiplying by $0$ doesn't change that. The best solution is probably to use an .m file to write a function with an IF to deal with this.

One "hack" which "works" is by changing the function to evaluate at $x+eps$

f = @(x) (sin(x+eps)./(x+eps))

0
On

Adapted from an accepted answer in MATLAB answers.

  1. Define original function $f$ as f = @(x) sin(x)/x;.
  2. Define target function $g$ as g = @(x) [f(x) 1]*sparse(1+isnan(f(x)),1,1,2,1);.

    • Example:

      x = .584; disp([g(x) sin(x)/x])  # return:    0.94412   0.94412
      x = 0; disp([g(x) sin(x)/x])     # return:    1   NaN
      
    • Exercise: Verify the above MATLAB code on (GNU) Octave Online thanks to free software technology.

Remarks: Comparison with Julia

This is much easier in Julia, another open source language whose syntax resembles MATLAB and Python but runs like C.

f(x) = (x == 0) ? 1 : sin(x)/x
f(1)     # returns 0.8414709848078965
f(0)     # returns 1
f(0.01)  # returns 0.9999833334166665
  • When $x = 0$, the conditional x == 0 make f returns $1$, and the code after : is ignored.
  • Otherwise, the rightmost part sin(x)/x is executed.