I have a problem in MATLAB. I want to calculate the nonlinear system of equation using Newton Method. This nonlinear system of equation is taken from finite difference method. The system is Ay=F(y) where $A$ is a $n-1$ by $n-1$ matrix, y is variable of solution y2, y3, ... yn, and F(y) is a function of y2, y3, ... yn. I try to make the MATLAB code as follows.
clear all;
clc;
fprintf('FINITE DIFFERENCE METHOD FOR NONLINEAR BVP ODE\n\n');
xa=0;
xb=2*pi;
N=50;
h=(xb-xa)/N;
x=xa:h:xb;
n=length(x);
% Matrix A
A=zeros(n-1,n-1);
A(1,1)=-2;
A(1,2)=1;
A(n-1,n-2)=2;
A(n-1,n-1)=-2;
for i=2:n-2
A(i,i-1)=1;
A(i,i)=-2;
A(i,i+1)=1;
end
%symbolic variable [y1;y2,...;yn]
y=sym('y',[n,1]);
%F
F=sym(zeros(n-1,1));
F(n-1)=h^2*sin(2*(x(n)))-h^2*sin(x(n))-h*y(n)*(2*h-2*h*y(n))-2*h+2*h*y(n);
for i=1:n-2
F(i)=h^2*sin(2*(x(i+1)))-h^2*sin(x(i+1))-h*y(i+1)*(y(i+2)-y(i));
end
%Non Linear System of Equation
G=A*y(2:n)-F;
%Newton Method
X0=zeros(n-1,1);% Initial Value for Newton Method
J=jacobian(G,y(2:n));
galat=1;
eps=1e-10;
k=1;
while galat>eps
JX0=double(subs(J,y(2:n),X0));
GX0=double(subs(G,y(2:n),X0));
X1=X0-JX0\GX0;
galat=norm(X1-X0);
X0=X1;
k=k+1;
end
ynum(1)=0;
ynum(2:n)=X1;%Solution for Newton Method
fprintf(' i xi yi yexc_i error\n');
for i=1:n
yeks(i)=sin(x(i));
error(i)=abs(ynum(i)-yeks(i));
fprintf('%3d %5.2f %8.10f %8.10f %10.10f\n',i,x(i),ynum(i),yeks(i),error(i));
end
subplot(2,1,1);
plot(x,ynum,'>','linewidth',1,'color','r','markerfacecolor','c');
hold on;
plot(x,yeks,'linewidth',1,'color','k');
hold on;
title(sprintf('Numerical solution and Exact Solution for h=%5.3f',h));
xlabel('x');
ylabel('y');
legend('y numerical','y exact');
grid on;
subplot(2,1,2);
plot(x,error,'-','color','r');
grid on;
title('Error');
xlabel('x');
ylabel('y');
But if I run the code, I have following error message:
Error using mupadengine/evalin2double
Unable to convert expression containing symbolic variables into double array. Apply 'subs' function first to substitute values for
variables.
Error in mupadengine/feval2double
Error in sym/double (line 756)
X = feval2double(symengine, "symobj::doubleDirect", S);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error in BHPPDNLND (line 38)
JX0=double(subs(J,y(2:n),X0));
^^^^^^^^^^^^^^^^^^^^^^^^^
Anyone know how to solve this problem? The code which have an error, the purpose is substituting the point X0 to jacobian matrix, so I have JX0 on the symbolic value form. I just want to convert the symbolic value to numerical value using double(), but the error message appear. Why this is can happen? Any help will be appreciated.
subsbefore callingdouble, you are only substituting for they(2:n). Therefore, your matrixJis still a function of the symbolic variabley1– try printing it out. You can't convert an object to floating point if it contains symbolic variables.