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

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

i'm getting error in fifth last line that is (x_1(i+1) = x_1(i)+ lambda*S(1);), where lambda is a variable and size of S is 2*1 and it contain numeric value i.e. [1/3 ; 1]. please someone help me to solve this.
i also tried vpa, sym(S) but getting same error.
Thank you in advance for the effort and time.

Sign in to comment.

 Accepted Answer

The norm() test is false the first time, so you do not assign to lambda, leaving it syms

4 Comments

const(j) = double(subs(g(j),[x1,x2], [x_1(i),x_2(i)]));
Remove the double() call so that const remains symbolic and so would be able to store symbolic lambda. Caution: you will need to figure out what max() means for an array that contains expressions in unresolved symbolic variables.
You should consider using
lambda = -inv(N'*N)*N'*double(subs(gradient(f),[x1,x2], [x_1(i),x_2(i)]));
near the beginning, after you first assign to x_1 and x_2, and not using syms lambda
By the way, I suggest you have a look at matlabFunction such as
H = matlabFunction(x1^2 - x1*x2*cos(x1-x2) -1, 'vars', {[x1, x2]})

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!