## Welcome to the World of Modelling and Simulation

### What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ... ### Newton-Raphson Method Codes for MATLAB

Newton-Raphson method is implemented here to determine the roots of a function. This algorithm is coded in MATLAB m-file. There are three files: func.m, dfunc.m and newtonraphson.m. The func.m defines the function, dfunc.m defines the derivative of the function and newtonraphson.m applies the Newton-Raphson method to determine the roots of a function.

Evaluating the root of sin(x):

func.m file
% defines the function as its roots to be determined

function [solution]=func(x)
solution=sin(x);

dfunc.m file
% defines the derivative of the function

function [dsolution]=dfunc(x)
dsolution=cos(x);

newtonraphson.m file
% applies Newton Raphson algorithm to determine the roots of a function

close all;
clear all;
x = input('Starting guess = ');
tolerance = 1e-8;
iterations = 0;
while (iterations<100) && (abs(func(x))>tolerance)
x = x-(func(x)/dfunc(x));
iterations = iterations + 1;
end
if iterations==100
disp('No root found')
else
disp(x)
end

Output:

Starting guess = 1

2.9236e-13

Starting guess = 0.1

1.2495e-11

Starting guess = 0.01

1.2335e-20

Evaluating the root of x-2*sin(xˆ2):

func.m file
% defines the function as it's roots to be determined

function [solution]=func(x)
solution = x-(2*sin(x.^2));

dfunc.m file
% defines the derivative of the function

function [dsolution]=dfunc(x)
dsolution=1-(4*x*cos(x));

Output:

Starting guess = 0.1

-1.0489e-10

Starting guess = 0.3

-2.4565e-10

Starting guess = 1

0.5055

Evaluating the root of x^2-5:

func.m file
% defines the function as it's roots to be determined

function [solution]=func(x)
solution = x^2-5;

dfunc.m file
% defines the derivative of the function

function [dsolution]=dfunc(x)
dsolution = (2*x);

Output:

Starting guess = 2

2.2361

Starting guess = 3

2.2361

Starting guess = 0.01

2.2361

#NewtonRaphson