How to correct the code?
Show older comments
I have to maximize the objective function with respect to x1 and x2.
func = -(x2*(-10)-x1*70+3*(80))
%Constrains are
3<=x1 ; x2<=8
This optimization has to be done in penality function method.
But my code has not working.
clc
clear
format long
syms x1 x2;
% objective function
func = -(x2*(-10)-x1*70+3*(80));
%Constrains
g1(1) = 3-x1;
g1(2) = x2-8;
eps = 0.001;
%initialize the convergance criteria
conv = 1;
% Initial Guess
i = 1;
x_1(i) = 3;
x_2(i) = 8;
rk(1) =0.001;
% addition of penality factor
f = func - rk(1)*(g1(1)+g1(2))
k = 1;
while conv > eps
Grad_f = gradient(f);
S = -subs(Grad_f,[x1,x2],[x_1(i),x_2(i)])
while norm(S)> eps
%calculate the step length
syms lambda
func_lambda = subs(f, [x1,x2], [x_1(i)+S(1)*lambda,x_2(i)+lambda*S(2)])
dfunc_lambda = (diff(func_lambda,lambda))
lambda = vpa(solve(dfunc_lambda==0,lambda),6);
lambda = lambda(imag(lambda)==0)
for k = 1:size(lambda)
fun_lambda_value(k) = subs(f,[x1,x2],[x_1(i)+lambda(k,1)*S(1),x_2(i)+lambda(k,1)*S(2)])
end
[value, index] = min(fun_lambda_value)
%compute the step length
lambda = lambda(index)
%replace the old value with new value for unconstrained
x_1(i+1) = x_1(i)+lambda*S(1)
x_2(i+1) = x_2(i)+lambda*S(2)
Grad_old = subs(Grad_f,[x1,x2],[x_1(i),x_2(i)])
i = i+1
Grad_new = subs(Grad_f,[x1,x2],[x_1(i),x_2(i)])
%update the search direction
S = -(Grad_new)+((norm(Grad_new))^2/(norm(Grad_old))^2)*S
end
Phi1 = subs(func,[x1,x2],[x_1(i-1),x_2(i-1)])
Phi2 = subs(func,[x1,x2],[x_1(i),x_2(i)])
conv = abs(abs(Phi2)-abs(Phi1))/abs(Phi1)
rk(k+1) = 0.01*rk(k)
k= k+1
end
Iter = 1:i;
K = 1:k
X_coordinate = x_1'
Y_coordinate = x_2'
Iterations = Iter'
Rk = rk'
for i=1:length(X_coordinate)
Objective_value(i) = double(subs(f,[x1,x2], [x_1(i),x_2(i)]))
end
Objective_value = Objective_value'
T = table(Iterations,X_coordinate,Y_coordinate, Objective_value)
I can't understand this error.How to rectify it?How to change the lamba as a empty system?
note: In function, -10,70,80 are changeable values.
Accepted Answer
More Answers (0)
Categories
Find more on Calculus in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
