0

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!

2 Answers 2

2

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{:}

0
0

You are creating anonymous functions, and they can be used with the following syntax:

myfun= @(x,y,z)([x*y*z,y^2,x+z])
res=myfun(1,2,3);
vect=[1 2 3]
res2=myfun(vect(1),vect(2),vect(3));

In general I would try to avoid using feval.

2
  • 1
    That works, however let's assume myfun has 10 unknowns, and then the vector has length 10 as well. Then it is a lot of work to write: res2=myfun(vect(1),vect(2),vect(3), vect(4), vect(5), vect(6), vect(7), vect(8), vect(9), vect(9)); isn't there an easier way to do this? Commented Apr 21, 2015 at 13:45
  • You are right, it is tedious. If you follow @thewaywewalk suggestions, you can get it with cell arrays. Commented Apr 21, 2015 at 13:49

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.