1

I am having trouble using fminsearch: getting the error that there were not enough input arguments for my function.

f = @(x1,x2,x3) x1.^2 + 3.*x2.^2 + 4.*x3.^2 - 2.*x1.*x2 + 5.*x1 + 3.*x2 + 2.*x3;
[x, val] = fminsearch(f,0)

Is there something wrong with my function? I keep getting errors anytime I want to use it as an input function with any other command.

fuesika
  • 3,280
  • 6
  • 26
  • 34

2 Answers2

3

I am having trouble using fminsearch [...]

Stop right there and think some more about the function you're trying to minimize.

Numerical optimization (which is what fminsearch does) is unnecessary, here. Your function is a quadratic function of vector x; in other words, its value at x can be expressed as

x^T A x + b^T x

where matrix A and vector b are defined as follows (using MATLAB notation):

A = [ 1 -1 0;
     -1  3 0;
      0  0 4]

and

b = [5 3 2].'

Because A is positive definite, your function has one and only one minimum, which can be computed in MATLAB with

x_sol = -0.5 * A \ b;

Now, if you're curious about the cause of the error you ran into, have a look at fuesika's answer; but do without fminsearch whenever you can.

Community
  • 1
  • 1
jub0bs
  • 60,866
  • 25
  • 183
  • 186
1

It is exactly what Matlab is telling you: your function expects three arguments. You are passing only one.

Instead of

[x, val] = fminsearch(f,0)

you should call it like

[x, val] = fminsearch(f,[0,0,0])

since you define the function f to accept a three dimensional vector as input only.

You can read more about the specification of fminsearch in the online documentation at http://mathworks.com/help/matlab/ref/fminsearch.html:

x = fminsearch(fun,x0) starts at the point x0 and returns a value x that is a local minimizer of the function described in fun. x0 can be a scalar, vector, or matrix. fun is a function_handle.

fuesika
  • 3,280
  • 6
  • 26
  • 34