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.

254 次查看(过去 30 天)
hello
i'm not an expert in matlab! when i run my code this error comes every time "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.
can anyone help me pleeeeeeese!
clear
close all
clc
syms x y
format short
f(x,y)=100*(y-(x^2))^2+(x-1)^2;
%gradient de la fonction:
g1=diff(f,x);
g2=diff(f,y);
grad=gradient(f(x,y),[x,y]);
g(x,y)=gradient(f(x,y),[x,y]);
hess=hessian(f(x,y),[x,y]);
%donnees du probleme:
x0=[0,1];
x1=[0,1];
alphaint=1;
beta=0.1;
taux=0.3;
N=100;
xn=x0;
%calcul du point critique avec le gradient:
for i=1:N
a=1;
d=-inv(hess)*g(x0(1),x0(2))
x0(1)=x0(1)+a*d(1);
x0(2)=x0(2)+a*d(2);
end
xfinal0=x0
%lignes de niveau de la fonction et points solution:
r=1:10;
fimplicit(f(x,y)==r)
grid on
hold on
plot(0,0,'*');
plot(xfinal0(1),xfinal0(2),'*')
hold off

回答(1 个)

Gouri Chennuru
Gouri Chennuru 2020-11-5
Hi,
As per my understanding, syms in MATLAB creates symbolic variables and functions.
In the for loop defined in the above code the variable "d" is of class sym and it contains the values shown below.
val =
1/(200*x^2 - 200*y + 1) - (200*x)/(200*x^2 - 200*y + 1)
val =
(2*x)/(200*x^2 - 200*y + 1) - (600*x^2 - 200*y + 1)/(200*x^2 - 200*y + 1)
As a workaround, symbolic substitution has to be done to the variable "d" so that it can be used to define variables x0 and x1 of class double.
This doesnt cause any error.
In order to do the symbolic substitution “subs” function is used in MATLAB.
Hope this Helps!

类别

Help CenterFile Exchange 中查找有关 Symbolic Math Toolbox 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by