I'm trying to ad a condition to an equation

5 visualizaciones (últimos 30 días)
Xavier Côté
Xavier Côté el 8 de Nov. de 2019
Editada: JESUS DAVID ARIZA ROYETH el 8 de Dic. de 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

Respuestas (2)

David Goodmanson
David Goodmanson el 8 de Nov. de 2019
Editada: David Goodmanson el 8 de Nov. de 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 comentario
Xavier Côté
Xavier Côté el 8 de Nov. de 2019
Thanks for the tips about the single scalar vs vector. I'm new to matlab and this one cause me a few problem.

Iniciar sesión para comentar.


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

Iniciar sesión para comentar.

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by