Professional Documents
Culture Documents
18/9/17 12:25 PM E:/Matlab/Cl249/Cranknicolson - SSJ.M 1 of 1: Function
18/9/17 12:25 PM E:/Matlab/Cl249/Cranknicolson - SSJ.M 1 of 1: Function
m 1 of 1
% initialize outputs
t = zeros(N+1,1);
x = zeros(N+1,length(x0));
x(1,:) = x0';
for i = 1:N
t(i+1) = t(i) + h;
% set up nonlinear equation solver
x_current = x(i,:)';
x_guess = x_current+h*fun(t(i),x_current);
disp(['For t = ' num2str(t(i+1))]);
% Newton Raphson routine
for ii = 1:iter_max
N1 = length(x_guess);
f = x_current + h/2*fun(t(i),x_current) + h/2*fun(t(i+1),x_guess) - x_guess;
% jacobian computation
J = h/2*jacobian(fun,t(i+1),x_guess) - eye(N1);
dx = GaussElimination_SSJ(J,-f);
x_new = x_guess +dx;
% check convergence
er = norm(x_current + h/2*fun(t(i),x_current)+ h/2*fun(t(i+1),x_new)-x_new);
if er < error_tol
disp(['Convergence achieved in ' num2str(ii) ' iterations']);
break; % stops iterations
else
% check if max iterations have reached
if ii == iter_max
disp('Maximum iterations reached without satisfying convergence
criteria');
else
% proceed to the next iteration with updated initial
% condition
x_guess = x_new;
end
end
end
x(i+1,:) = x_new';
end