I'm trying to ad a condition to an equation
5 views (last 30 days)
Show older comments
I'm trying to write an equation like
fx=@(x) sin(x)^2/x
But i need to add a condition to avoid a division by zero.
I've manage to do just that by writing a function but it seem to overcomplicate everything.
function [fx]=fv(x)
if x == 0
fx=x;
else
fx=sin(x)^2/x;
end
end
Any idea would help me a lot.
Thanks
0 Comments
Answers (2)
David Goodmanson
on 8 Nov 2019
Edited: David Goodmanson
on 8 Nov 2019
Hi Xavier,
I don't think your original function is overcomplicated at all. It's straightforward code that is self-commenting, which is very much in its favor. Even clearer would be
function fx = fv(x)
if x == 0
fx = 0; <---
else
fx=sin(x)^2/x;
end
end
Jesus Royeth's previous answer works well, but what if you ran up against this piece of code a few years from now?
fx=@(x) (x~=0)*sin(x)^2/(x+(x==0))
What is it up to? It needs a comment (I don't think Jesus is implying at all that it would not need one in working code):
fx = @(x) (x~=0)*sin(x)^2/(x+(x==0)) % impose fx(0) = 0
An important consideration is that the function only works for a single scalar input, and while that is okay, Matlab operates very much in a vector and matrix environment. Here is a version that uses ./ and .^ to allow element-by-element operations on vector input:
function fx = fv(x)
fx = sin(x).^2./x;
fx(x==0) = 0;
end
The idea here is than any instances of x = 0 produce 0/0 = NaN, and the second line takes care of those.
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!