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

조회 수: 25 (최근 30일)
Adam Attarian
Adam Attarian 2011년 10월 28일
댓글: Walter Roberson 2022년 3월 26일
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일
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
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개)

카테고리

Help CenterFile Exchange에서 Performance and Memory에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by