I'm trying to ad a condition to an equation

4 vues (au cours des 30 derniers jours)
Xavier Côté
Xavier Côté le 8 Nov 2019
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

Réponses (2)

David Goodmanson
David Goodmanson le 8 Nov 2019
Modifié(e) : David Goodmanson le 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.
  1 commentaire
Xavier Côté
Xavier Côté le 8 Nov 2019
Thanks for the tips about the single scalar vs vector. I'm new to matlab and this one cause me a few problem.

Connectez-vous pour commenter.


JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH le 8 Nov 2019
a trick:
fx=@(x) (x~=0)*sin(x)^2/(x+(x==0))
  4 commentaires
Xavier Côté
Xavier Côté le 8 Nov 2019
Perfect. Clever simple. Exactly what I was looking for.
darova
darova le 8 Nov 2019
Works without (x~=0) too
123.PNG

Connectez-vous pour commenter.

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by