I implemented a piecewise function using an anonymous function that can also be evaluated in vectors or matrices:
f = @(x) exp(((x-.25).*(x-.75)).^-1) .* (.25 < x & x < .75);
The problem is when evaluating it at exactly 0.25
or 0.75
we try to evaluate Inf * 0
which results in NaN
. I would like to set these NaN
values to zero. I am aware that this can easily be done using a function defined in a file, but I'm wondering whether there is a solution that would let you do this inline. (Possible defining other anonymous helper functions.)
To get rid of the NaN
's, you can exploit the fact that some functions like max
ignore NaN
's:
>> max(NaN, 0)
ans =
0
which also works vectorized:
>> max([1 2 NaN 4], 0)
ans =
1 2 0 4
The mathematical function you are working with is non-negative. So if y
is an array resulting from the anonymous function as defined in your question, max(y, NaN)
will leave numeric entries of y
untouched, and will transform NaN
into 0
.
In conclusion, modify the anonymous function to include an outer max(..., 0)
:
f = @(x) max(exp(((x-.25).*(x-.75)).^-1) .* (.25 < x & x < .75), 0);
This gives, for example,
>> f([.2 .25 .4 .5 .6 .75 .8])
ans =
1.0e-06 *
0 0 0.0053 0.1125 0.0053 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With