Matlab declare function with two different behaviours

89 Views Asked by At

I'm struggling in finding a way to declare a function with two different behaviours in the following way:

$$f(x) = \begin{cases} \frac{\sin(x)}{x} & \text{if } x \neq 0, \\ 1 & \text{if } x = 0. \end{cases} $$

Thanks

1

There are 1 best solutions below

0
On

Here is a simple example:

function y = f(x)
    if x==0
        y = 1;
    else
        y = sin(x)/x;
    end
endfunction

Here is a vectorised example:

function y = f(x)
    # return array must have same size as x...
    y = 0*x;
    # logical array with conditional...
    idx = x==0;
    y(idx) = 1;
    y(!idx) = sin(x(!idx))./x(!idx);
endfunction

Note that in the above it would make more sense to compute !idx, but the purpose is here to illustrate.