4

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?

Richard Povinelli
  • 1,419
  • 1
  • 14
  • 28
Harshveer Singh
  • 4,037
  • 7
  • 37
  • 45

2 Answers2

6

Have you tried it? The best way to learn a tool like matlab is to try things!

In fact, you don't even need to create an m-file function. I'll do it using a function handle here.

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

ans =
      -3.8357

I could have defined f1 as an m-file function too, but that would have required I save a file. Why bother?

5

What you are looking for is the function handle.

You can obtain the function handle of a function (in the following case, sqrt) 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 be as if you are using the sqrt function.

For more details, you may also refer to another Stackoverflow question: function handle in MATLAB

Community
  • 1
  • 1
YYC
  • 1,792
  • 1
  • 14
  • 19