I'm trying to ad a condition to an equation

5 ビュー (過去 30 日間)
Xavier Côté
Xavier Côté 2019 年 11 月 8 日
編集済み: JESUS DAVID ARIZA ROYETH 2019 年 12 月 8 日
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

回答 (2 件)

David Goodmanson
David Goodmanson 2019 年 11 月 8 日
編集済み: David Goodmanson 2019 年 11 月 8 日
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 件のコメント
Xavier Côté
Xavier Côté 2019 年 11 月 8 日
Thanks for the tips about the single scalar vs vector. I'm new to matlab and this one cause me a few problem.

サインインしてコメントする。


JESUS DAVID ARIZA ROYETH
JESUS DAVID ARIZA ROYETH 2019 年 11 月 8 日
a trick:
fx=@(x) (x~=0)*sin(x)^2/(x+(x==0))
  4 件のコメント
Xavier Côté
Xavier Côté 2019 年 11 月 8 日
Perfect. Clever simple. Exactly what I was looking for.
darova
darova 2019 年 11 月 8 日
Works without (x~=0) too
123.PNG

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by