The following error occurred converting from sym to double: Unable to convert expression containing symbolic variables into double array. Apply 'subs' function first to substitute values for variables
Show older comments
clc
clear
format long
% Function Definition (Enter your Function here):
syms x1 x2 lambda k;
%Optimization function
f = (x1-1)^2 +(x2-2)^2 -4;
%Constrains :
g(1) = x1+2*x2-5;
g(2) = 4*x1 +3*x2-10;
g(3) = 6*x1+x2-7;
g(4) = -x1;
g(5) = -x2;
N = 5; %number of constraints
%tolerances
eps1 = 0.00001;
conv = 1; %initialize the convergance criteria
% Initial Guess (Choose Initial Guesses):
i = 1
x_1(i) = 0.5;
x_2(i) = 0.5;
%search direction
Search_dir = -gradient(f);
% function value and constraints at initial guess
fun_value = double(subs(f,[x1,x2], [x_1(i),x_2(i)]));
while conv > eps1
I = [x_1(i),x_2(i)]';
for j = 1:N
const(j) = double(subs(g(j),[x1,x2], [x_1(i),x_2(i)]));
end
S = subs(Search_dir,[x1,x2], [x_1(1),x_2(1)]);
S = S/max(abs(S(1)),abs(S(2))); %normalize in suitable manner
if max(const) ~= 0
%go for feasible direction
S = S;
else
for j = 1:N
if const(j)==0
N = double(subs(gradient(g(j)),[x1,x2], [x_1(i),x_2(i)]));
P = eye(2)-(N*inv(N'*N)*N');
S1 = double(P*double(subs(gradient(f),[x1,x2], [x_1(i),x_2(i)])));
S = S1/norm(S1);
end
end
end
%step length
if norm(S)<= eps1
lambda = -inv(N'*N)*N'*double(subs(gradient(f),[x1,x2], [x_1(i),x_2(i)]));
if lambda>0
optima = [x_1(i),x_2(i)];
optimum = double(subs(f,[x1,x2], [x_1(i),x_2(i)]));
break;
end
else
x_1(i+1) = x_1(i)+ lambda*S(1);
x_2(i+1) = x_2(i)+ lambda*S(2);
for j = 1:N
const(j) = vpa(subs(g(j),[x1,x2], [x_1(i)+ lambda*S(1),x_2(i)+ lambda*S(2)]));
end
1 Comment
Narayan Das Ahirwar
on 24 Dec 2020
Accepted Answer
More Answers (0)
Categories
Find more on Matrix Indexing 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!