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

 Accepted Answer

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 Comments

Thanks -- this totally does the trick. And vectorization for free!
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.
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.
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.
What if the value to be returned is a string?
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

Sign in to comment.

More Answers (0)

Categories

Community Treasure Hunt

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

Start Hunting!