27

I'm trying to write a function that is gets two arrays and the name of another function as arguments.

e.g.

main.m:

    x=[0 0.2 0.4 0.6 0.8 1.0];
    y=[0 0.2 0.4 0.6 0.8 1.0];

    func2(x,y,'func2eq')

func 2.m :
    function t =func2(x, y, z, 'func')   //"unexpected matlab expression" error message here    
    t= func(x,y,z);

func2eq.m:  
    function z= func2eq(x,y)

    z= x + sin(pi * x)* exp(y);

Matlab tells gives me the above error message. I've never passed a function name as an argument before. Where am I going wrong?

pb2q
  • 58,613
  • 19
  • 146
  • 147
Meir
  • 12,285
  • 19
  • 58
  • 70

2 Answers2

41

You could also use function handles rather than strings, like so:

main.m:

...
func2(x, y, @func2eq); % The "@" operator creates a "function handle"

This simplifies func2.m:

function t = func2(x, y, fcnHandle)
    t = fcnHandle(x, y);
end

For more info, see the documentation on function handles

Leo
  • 142
  • 10
Edric
  • 23,676
  • 2
  • 38
  • 40
10

You could try in func2.m:

function t = func2(x, y, funcName)  % no quotes around funcName
    func = str2func(funcName)
    t = func(x, y)
end
nbro
  • 15,395
  • 32
  • 113
  • 196
Matt Bridges
  • 48,277
  • 7
  • 47
  • 61
  • At least in v. 2015, if you don't quote the funcName, MATLAB interpreter expects arguments to be supplied. were you thinking that funcName is a handle? – Carl Witthoft Aug 15 '19 at 12:17