Brian
Brian

Reputation: 27392

multiple step anonymous functions

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

Answers (2)

Franck Dernoncourt
Franck Dernoncourt

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

Jonas
Jonas

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

Related Questions