Ali Eslami
Ali Eslami

Reputation: 25

Minimizing a function using Lagrange multipliers in matlab

I have a problem with my MATLAB code that I write to minimize this function with two constraints (one of them is inequality and the other one is equality) with Lagrange Multipliers that use KKT conditions. This the Function :

       MIN F = 2*x1^2 + 2*x2^2-6*x1*x2
        ineq=x1+2*x2<=3
        eq=3*x1+x2=9

I am personally suspect that my if Function(statement) has problem but don't know how to fix that .....

    clc
    warning off
    syms x1 x2 u s lambda
    f=2*x1^2+2*x2^2-6*x1*x2;
    g1=sqrt(x1^2*x2)+s^2-0.25;
    H1=x1*x2^2-0.1;
    Lagrange=f+u*g1+lambda*H1;
    Grad=gradient(Lagrange);
    S=solve(Grad);
    S=double([S.x1 S.x2 S.s S.u S.lambda]);M=size(S,1);
      for i=M:-1:1
    if imag(S(i,3))~=0 || S(i,1)<=0 || S(i,2)<=0
      end
    end
    x1=S(:,1);x2=S(:,2);s=S(:,3);u=S(:,4);lambda=S(:,5);
    out=table(x1,x2,s,u,lambda)
    x0=[1 0.5 -0.75];

It seems I have a problem because it gives me both write and wrong answers can you help me with that ?

Upvotes: 1

Views: 1558

Answers (1)

Adam
Adam

Reputation: 2777

Just eliminate the corresponding row when if condition is satisfied using S(i,:)=[];


According to your formulation

The if condition should look like this

if imag(S(i,3))~=0 || S(i,1)<=0 || S(i,2)<=0
    S(i,:)=[];
end

Solution

out =

  1×5 table

      x1        x2       s      u       lambda 
    ______    _______    _    ______    _______

    0.3393    0.54288    0    3.6349    -2.6402

From my point of view your equality and inequality constraints formulation are wrong

ineq = x1 + 2*x2 <= 3 -------> g1 = x1 + 2*x2 - 3 + s^2

eq = 3*x1 + x2 = 9    -------> H1 = 3*x1 + x2 - 9

The if condition checks

  • if u(modifying g1) is less than zero or not

or

  • if s is real number or not
for i=M:-1:1
      if imag(S(i,3))~=0 || S(i,4)<0 
      S(i,:)=[];
      end
  end

The entire code is as follow

syms x1 x2 u s lambda
    f=2*x1^2+2*x2^2-6*x1*x2;
    g1 = x1+2*x2-3 +s^2 ;
    H1 = 3*x1+x2-9;

    Lagrange=f+u*g1+lambda*H1;
    Grad=gradient(Lagrange);

    S=solve(Grad)
 S=double([S.x1 S.x2 S.s S.u S.lambda]);M=size(S,1)

      for i=M:-1:1
          if imag(S(i,3))~=0 || S(i,4)<0 

             S(i,:)=[];

          end
      end

    x1=S(:,1);x2=S(:,2);s=S(:,3);u=S(:,4);lambda=S(:,5);
    out=table(x1,x2,s,u,lambda)

Solution

out =

  1×5 table

    x1    x2    s     u      lambda
    __    __    _    ____    ______

    3     0     0    13.2     -8.4 

Check your answer using fmincon as follow

% Check your answer using fmincon 
% Inequality constraint
%ineq = x1 + 2*x2 <= 3
A = [1, 2];
b = 3;
% Equality constraint
%eq = 3*x1 + x2 = 9
Aeq = [3, 1];
beq = 9;
%F = 2*x1^2 + 2*x2^2-6*x1*x2
F = @(x)2*x(1).^2 + 2*x(2).^2-6*x(1).*x(2);

x0 = [0,0];
[x_minimum, Feval] = fmincon(F, x0, A, b, Aeq, beq);

Solution

x_minimum =

    3.0000   -0.0000


Feval =

   18.0002

Upvotes: 1

Related Questions