Anonymous functions and conditional logic? (one line step function)

Hi Folks,
It looks like you can't use conditional logic in an anonymous function -- which is too bad because I'm trying to do a step function as an anon function. I'd like to do it as a one liner, something like:
step = @(t) if t>t0 return a, elseif t<=t0 return b, end,
but MATLAB doesn't like that of course. In my case, a=10e-4 and b=10e-6, just in case anyone is wondering. Is there something similar that I can do? I've been trying to modify tanh(x) to go from a to b, but I can't quite get the syntax right. I'd like an anon fun because it would be an element in a structure array if I get this coded right.
Thanks for the help! Adam

 採用された回答

Fangjun Jiang
Fangjun Jiang 2011 年 10 月 28 日

1 投票

It can be done in a twisted way. I am not sure how much value it provides. step is a built-in function so avoid using it.
h=@(t) a*(t>5)+b*(t<=5)
or with the complete parameters
h=@(t,t0,a,b) a*(t>t0)+b*(t<=t0)

6 件のコメント

Adam Attarian
Adam Attarian 2011 年 10 月 28 日
Thanks -- this totally does the trick. And vectorization for free!
Walter Roberson
Walter Roberson 2011 年 10 月 28 日
Warning: this trick does not work if the "unselected" calculation happens to be infinite. For example if you were to try
1/x * (x~=0) + 1 * (x==0)
then for x=0, aslthough the x~=0 would be false, it would be false multiplied by 1/0 which is 0 * infinity which is defined as NaN.
There is a safer version using subsref.
hosein Javan
hosein Javan 2017 年 8 月 5 日
this way you can define a piecewise anonymous function:
f=@(x) [x(x<1).^2 , x(x>=1)]
the function is x^2 for x<1 and x for x>=1. use fplot to check it out.
Walter Roberson
Walter Roberson 2017 年 8 月 5 日
Interesting approach, hosein Javan, but for vector x, that potentially re-orders the outputs. For example let x = rand(1,20)*2; then your code would put all of the results for x in (0,1) into the left side and the results for [1,2) into the right side instead of having them in order of x.
Piyush Kant
Piyush Kant 2022 年 3 月 26 日
What if the value to be returned is a string?
Walter Roberson
Walter Roberson 2022 年 3 月 26 日
In the case of string objects I would suggest having a string array being indexed by (2 minus logical value). This would select the first string for true and the second for false

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangePerformance and Memory についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by