Defining a function in Matlab that uses a function as a parameter

I want to define a function like this:

function f = f1(fun,a,b,c) f = c*fun(a+b); 

Here fun is some function that I will pass when I use the function f . How can I do this in matlab?

+4
source share
2 answers

You tried? The best way to learn a tool like Matlab is to try something!

In fact, you don’t even need to create an m file function. I will do this with a function descriptor.

 fun = @(x) sin(x); f1 = @(f,a,b,c) c*f(a+b); f1(fun,2,3,4) ans = -3.8357 

I could define f1 as a function of the m file, but that would require saving the file. Why bother?

+6
source

What you are looking for is a function descriptor .

You can get the function descriptor of a function ( sqrt in the following case) by placing the "at" ("@") symbol in front of the function name:

 a = 1; b = 2; c = 3; fun = @sqrt; % obtain the function handle of sqrt() f = f1(fun, a,b,c); % pass the function handle of sqrt() into your function f1(). 

When you use fun , it will look like you are using the sqrt function.

For more information, you can also refer to another question about Stackoverflow: function descriptor in MATLAB

+5
source

Source: https://habr.com/ru/post/1392243/


All Articles