MATLAB Need help with matlab code for Newton-raphson ( really bad)

AI Thread Summary
The discussion centers on a code issue where the user is receiving incorrect outputs from a numerical method implementation, specifically the Newton-Raphson method. The provided function and Jacobian definitions are causing the algorithm to return infinite or NaN values. The key point of contention is that the Jacobian matrix, J, must be defined as a 3x3 matrix of derivatives rather than a vector. This misunderstanding leads to the failure of the algorithm, resulting in erroneous outputs. The user is advised to correct the Jacobian definition to ensure proper convergence and valid results from the method.
fizzkilla
Messages
4
Reaction score
0
The code runs but I get the wrong answers can you take a look at the code for this .

ANSWERS
******************
x(1) = 1.035
x(2) = 1.086
x(3) = 0.927
******************

clc
clear


F = @(x) [15*x(1)+(x(2)^2)-4*x(3)-13;...
(x(1)^2)+10*x(2)^2-x(3)-11;...
x(2)^2-25*x(3)+22];
J = @(x) [15+2*x(2)-4;2*x(1)+10-1;0+2*x(2)-25];

xo = [1 1 1];
n = 4;


es = .5*10^(2-n);

[xn,cnt] = Newton_raphson(es,xo,J,F);


fprintf('******************\n')
for i = 1:length(xo)
fprintf(' x(%d) = %.3f\n',i',xn(i)')
end
fprintf('******************\n')
fprintf('It took %d iterations to converge!\n',cnt')

FUNCTION PROGRAM


function [xn, cnt] = Newton_raphson(es,xo,J,F)

cnt = 0;
ea = 1;

while ea > es
delx = J(xo)\-F(xo);
xn = xo + delx;

ea = 100*max(abs((xn - xo) ./ xn));
xo = xn;
cnt = cnt + 1;

end
 
Physics news on Phys.org
J should be a 3 x 3 matrix of derivatives with ##J_{ij} = \partial F_i / \partial x_j##, not a vector.
 
Ok then after now I get answers like inf inf and nan
 
Back
Top