Reputation: 27392
I have a rather complicated function the I would like to write as an anonymous function.
It looks something like this:
function Answer = MatlabFunction(x)
a=4*x;
b=sin(a);
c=cos(b);
Answer = c;
I don't know how to put this into an anonymous function however. Is there a way to do this without writing it as several cascading functions?
Upvotes: 2
Views: 2935
Reputation: 83147
Matlab is notorious for not supporting multiple step anonymous functions. There existing however some ugly tricks to circumvent this limitation. http://www.mathworks.com/matlabcentral/answers/50195-is-it-possible-to-write-several-statements-into-an-anonymous-function presents a few ones, e.g:
An if/else can be coded in function form by using:
FHEXEC = @(FH) FH(); FHSELECT = @(TF,CONDITION) TF(CONDITION==[true,false]); IF = @(CONDITION,TRUEFUNC,FALSEFUNC) FHEXEC( FHSELECT([TRUEFUNC,FALSEFUNC],CONDITION) )
Upvotes: 0
Reputation: 74930
There are two ways:
Either, you save your function MatlabFunction
on the Matlab path, and define your anonymous function as
myFun = @MatlabFunction;
Or, you define the function directly as
myFun = @(x)cos(sin(4*x));
Upvotes: 3