user466534
user466534

Reputation:

Nonlinear square optimization task in matlab

let us suppose that we have following task:Find the optimal value of weights

enter image description here

so that minimize following equation

enter image description here

where var-means variance of given x1 variable, also we have constraint that sum of these weights should be equal to 1 enter image description here

i have initialized anonymous function and weights for initial points

w=[0.5; 0.5];


  >> f=@(x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))

f = 

    @(x1,x2)(w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))

i think i should use function fmincon, i have created A matrix

A=[1;1];

and b column

b=[1];

then i tried following fun

weighs=fmincon(f(x1,x2),w,A,b)

but it gives me error

Error using optimfcnchk (line 287)
FUN must be a function, a valid string expression, or an inline function
object.

could you help me please what is wrong? thanks in advance

Upvotes: 2

Views: 81

Answers (1)

Jonas
Jonas

Reputation: 74940

You need to specify the function in fmincon as a function handle or anonymous function; f(x1,x2) evaluates to a scalar double, not a function handle. fmincon will want to evaluate this function with current values of w to check for the quality of the solution, so it needs a way to feed w as an input.

Thus, you need to

  • Change the function definition to f(w,x1,x2), i.e. f=@(w,x1,x2) (w(1)*w(1)*var(x1)+w(2)*w(2)*var(x2))
  • Write the fmincon call as fmincon(@(u)f(u,x1,x2),...)

However, I would suggest to substitute 1-w(2) for w(1) (or vice versa) in your problem to reformulate it as an unconstrained optimization of one variable (unless w is a real weight, and has to remain between 0 and 1, in which case you still need a constraint).

Upvotes: 2

Related Questions