Conditional function creating with @ handle

29 ビュー (過去 30 日間)
Ashok Das
Ashok Das 2019 年 2 月 15 日
コメント済み: Walter Roberson 2019 年 2 月 15 日
If I want to make a function f(x,y) = x+y, we do
f= @(x,y) x+y
Now I want to create a function of the form, f(x,y) = x+y if x*y >1 ; x-y if x*y <=1.
How should I create it with a @ handle?
Thanks in advance

採用された回答

Stephen23
Stephen23 2019 年 2 月 15 日
編集済み: Stephen23 2019 年 2 月 15 日
Directly for this specific calculation:
>> f = @(x,y) x + y*(1-2*((x*y)<=1));
>> f(1,2)
ans = 3
>> f(2,1)
ans = 3
It works by simply defining the sign here:
(1-2*((x*y)<=1))
and using that sign to multiply with y. The inbuilt sign function cannot be used because it returns 0 when the input is 0.
  1 件のコメント
Ashok Das
Ashok Das 2019 年 2 月 15 日
Thanks. :)

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2019 年 2 月 15 日
@(xx,yy) (xx+yy).*(xx*yy>0) + (xx-yy).*(xx*yy<0)
note that this will fail if xx or yy are infinite.
  3 件のコメント
Stephen23
Stephen23 2019 年 2 月 15 日
+1 general solution
Walter Roberson
Walter Roberson 2019 年 2 月 15 日
If you have the symbolic toolbox, it is often the case that such things are better rewritten in terms of piecewise()
If you happen to be using integration, then with complicated formula, numeric integration using multiplication by a logical condition can turn out to be much faster than symbolic integration. However, numeric integration is not always sufficiently sensitive to narrow regions, and narrow regions sometimes make a huge difference in integration. For example, numeric integration will almost always get the wrong results if there is a dirac delta in the calculation, unless you happen to drop in a waypoint right at the location of every delta (and integral2 does not permit waypoint specification at all.)

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

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by