Site logo MA251: Calculus I
MA251
Readings
Problems
Matlab
Newton's method is an algorithm that is extremely easy to implement in Matlab. Recall that the formula for Newton's Method is:
x_{n+1} = x_n - \frac{f(x_n)}{f'(x_n)}\,\!.
To implement this in Matlab all you have to do is the following:

syms x
f = x^2-2
df = diff(f)
X = 2;
X = X-subs(f,x,X)/subs(df,x,X)

In this example, we were looking for the root of the function f(x)=x^2-2 with a starting value x1 = 2. Therefore, to implement another function we just have to change two lines f=x^2-2 with the new function and X=2 with the new starting value.

For many problems, it may be beneficial for Matlab to run the code 1000 times instead of you pushing the up arrow and return a thousand times. This is very easy to do in Matlab with a loop.

for i = 2:1000
i
X = X-subs(f,x,X)/subs(df,x,X)
end

Notice that this code tells Matlab to calculate x2 through x1000. The second line tells Matlab to spit out the index i (since there is no semicolon at the end). The third line tells Matlab to spit out the Newton iterates. Again you could tell Matlab not to spit them out by adding a semicolon at the end.

THAT'S ALL FOLKS!