Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function to a function in matlab [duplicate]

How can I pass a function into another in matlab:

For example assume this function works as optimizer :

    Function [returnValue]=optimizer(@myfunction)
    %function definition
    End

How can I call optimizer function to optimize myfunction?

like image 471
mefmef Avatar asked Dec 23 '11 10:12

mefmef


People also ask

Can you pass a function into a function?

Functions can be passed into other functions Functions, like any other object, can be passed as an argument to another function.

Can a MATLAB function call another function?

If you put those two functions in a function file and try to call hahaha from the MATLAB prompt, MATLAB will error. Only the main function in a function file (the first one in the file) is directly callable by code outside that file. f would be a function handle to the local function.

How do you repeat a function in MATLAB?

repeat( action , n ) repeats the same action n times. You can specify the input arguments in any order. That is, repeat(action,n) and repeat(n,action) both repeat the action n times.


2 Answers

You can do as follow:

function optimizer(f)
...
x=0;
y=f(x);
...
end

And you call it like that:

f=@(x) (x^2); 
optimizer(f)
like image 73
Oli Avatar answered Oct 06 '22 14:10

Oli


Matlab has function handles which enables you to pass function pointers around.

like image 8
Niklas B. Avatar answered Oct 06 '22 15:10

Niklas B.