简体   繁体   中英

matlab objective funtion must return a scalar value

I am trying to understand now fminunc (fmincon) works, however I keep getting error.

When I use documentation example with two variables

fun = @(x)3*x(1)^2 + 2*x(1)*x(2) + x(2)^2 - 4*x(1) + 5*x(2);
x0 = [1,1];
[x,fval] = fminunc(fun,x0);

everything works fine.

Hovewer, when I am trying to fit a plane for 3 points, the code does not work

n0 = [ 0  1 -2; 
       1  2  1;
      -2 -4 -4]
fun = @(x) [x(1) x(2) x(3)] * n0 - [1 1 1]

The task for fminunc is just an example. I know I can solve it easily analytically.

The cost function returns a scalar. What you have written returns a [1x3] matrix. You could try something like this if you want to minimise the euclidean distance

fun = @(x) sum(([x(1) x(2) x(3)] * n0 - [1 1 1]).^2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM