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

Click For Summary
SUMMARY

The forum discussion focuses on troubleshooting a MATLAB implementation of the Newton-Raphson method for solving a system of nonlinear equations. The user reports that the code runs but produces incorrect results, specifically infinite and NaN values. The Jacobian matrix, defined as J, is incorrectly structured as a vector instead of a 3x3 matrix of derivatives. Correcting this structure is essential for the algorithm to converge properly.

PREREQUISITES
  • Understanding of the Newton-Raphson method for solving nonlinear equations
  • Familiarity with MATLAB syntax and function definitions
  • Knowledge of Jacobian matrices and their role in optimization
  • Basic concepts of convergence criteria in numerical methods
NEXT STEPS
  • Review MATLAB function handles and anonymous functions
  • Learn about constructing Jacobian matrices in MATLAB
  • Explore convergence criteria for iterative methods in numerical analysis
  • Investigate error handling in MATLAB to manage infinite and NaN values
USEFUL FOR

MATLAB programmers, numerical analysts, and students studying numerical methods who are looking to implement or troubleshoot the Newton-Raphson method for solving systems of equations.

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
 

Similar threads

Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 3 ·
Replies
3
Views
5K
  • · Replies 29 ·
Replies
29
Views
5K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 1 ·
Replies
1
Views
4K
  • · Replies 9 ·
Replies
9
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
7
Views
9K