Search code examples
matlabfunctionnumerical-methodsevaluate

Evaluate multiple values in a function matlab


I have defined a function in matlab:

function1 = @(x,y,z)[x*y*z,y^2,x+z]

Then in the program I want to writ, I want to evaluate the values of this function for (1,2,3).

Outside the program I can use feval(function1,1,2,3) and this returns

6     4     4.

Now inside my program, I want the input to be like this: output = program(fun, vec), where vec is a vector like [1,2,3].

If I now call: feval(fun,vec) I get the following error message:

Error using @(x,y,z)[x*y*z,y^2,x+z]
Not enough input arguments.

Can someone tell me how I can evaluate the values of my function when the input is a vector instead of three seperate numbers?

Many thanks!


Solution

  • You need a comma-separated list. Define your vector vec as follows:

    vec = {1 2 3} 
    

    or use

    vec = [1 2 3]
    vec = num2cell{vec}
    

    and then call feval:

    feval(fun,vec{:})
    

    It is actually obsolete to evaluate functions with feval, the following is equivalent:

    function1(1,2,3)
    function1(vec{:})
    

    As you want to pass the vector vec to your program you need to modify your program to either accepted a various number of inputs with varargin:

    program(fun, vec{:))
    

    or you change the evaluation of vec inside your function to vec{:}