Newton-Raphson method (interactive command window in MATLAB)

Vegeedog
Numerical Methods
Published in
3 min readJun 10, 2022

--

Intro: Solving nonlinear function is not quite feasible using analytical methods. Instead, we could turn to iterative, numerical methods. That is, starting with some initial guess value, then updates value in each iteration, which creates a sequence of values (x0, x1, ….. xn) that hopefully, would finally converge to the actual roots of the function f(x).

There are 3 common approaches: 1. Bisection 2. Newton-Raphson 3. Secant. Here, we would implement Newton-Raphson, which normally converges much faster than Bisection method, and requires only 1 initial value.

Derivation:

MATLAB implementation:

To start with, need to specify the function f(x) & its differential function f’(x). Then, we would plot the function f(x) to help user to how does the function look like within a specified range of x. After showing the image, it would show a menu, providing 3 commands:

1. Zoom in (i.e., change the range of x)

2. Set initial value (i.e., set the starting point x0, and then start to run the Newton-Raphson method to find the root of function)

3. Quit (i.e., exit the program)

After executing one command, the menu would show again, until the user chooses the 3rd option: Quit.

Write in two MATLAB file. One for the menu (‘itermenu.m’), the other one for the main program (‘mynewton.m’).

Menu (would be called in the main program)

Main program

There are multiple steps that requires user input and are simply done by MATLAB built-in functions, in additional to the normally used input(‘…’) function.

At first, user need to specify y(x) & y’(x), after the instructions. The ‘keyboard’ command gives control to the user, enabling user to type in the functions as strings and save in variables, until user types ‘dbcont’. The image below shows how it actually works.

Give the function y(x) and its derivative as string variables:
for example, y = ‘x — sin(x) — 1’
or any other function of x
and dydx = ‘1 — cos(x)’
specify here the correct derivative of y(x)
then leave the input mode — type ‘dbcont’, then <enter>
K>> y = ‘x⁴-3*x³+x²-2*x+2’

y =

‘x⁴-3*x³+x²-2*x+2’

K>> dydx = ‘4*x³-9*x²+2*x-2’

dydx =

‘4*x³-9*x²+2*x-2’

K>> dbcont

Then it would plot the image, giving a brief look of the function. Use the function ‘pause’ here, pause the execution of program and let the user examine the image, and then one could press any button to continue.

After switching back to the command window, the main program calls the ‘itermenu.m’ to display the menu. Option2 is to run Newton Raphson algorithm to iteratively find the root of y(x). At line 61, ‘[x, yg] = ginput(1)’, would show a cursor, which user could drag to the desired x location in the plot. And this x would be set as the initial point, x0.

--

--