fminsearch multiple parameters matlab

Joanna picture Joanna · Jan 23, 2015 · Viewed 9.5k times · Source

I'm trying to use fminsearch with multiple parameters but I can't seem to even get it working with two. I've also tried using optimization tool in matlab but then I get:

Optimization running.
Error running optimization.
Not enough input arguments. 

What i do:

fval = fminsearch(@g,[1 1])

The function g looks like this:

function r=g(x,y)
   r=x.^3+3*x*y.^2+12*x*y;
end

but i get this:

Error using g (line 2)
Not enough input arguments.

Error in fminsearch (line 190)
fv(:,1) = funfcn(x,varargin{:});

Answer

David picture David · Jan 23, 2015

Your function g takes two inputs, x and y, however you supply fminsearch one input, the vector [1 1]. You need to rewrite it so that fminsearch only needs a single vector as input, but then that vector is split into two numbers to input into g.

fminsearch(@(v) g(v(1),v(2)),[1 1])

This makes an anonymous function that takes a vector as input (v) and then uses the first element (v(1)) as the first input to g, and the second element as the second input.