It is clearly laborious and time-wasting to carry out each iteration by hand. Therefore in this section we will add code to iteration.m that will carry out the iteration procedure automatically.
The first thing to do is to add a MATLAB
input statement to iteration.m that asks you to input the
starting value for the iteration i.e.
. In MATLAB you must call this
x(1)
as MATLAB does not recognise zero indices for vectors.
It is also useful to add the command
format long
at this stage,
in order to be able to check the accuracy of your results.
Now include a
for-loop
running from
to
that will calculate the next twenty iterates
. Remember that in MATLAB these will be the vector
elements x(2), x(3), ..., x(21). You should also include
a line of code like
disp([ n+1 x(n+1) ])
(see
Displaying output) that will
print the iterate number and the new iterate each time through the loop.
Save iteration.m and run the program, starting
with a value
.
The process of fixed-point iteration is only useful
if the iterates
converge to the true solution
. In the
notes we prove that if successive iterates converge, then the iterates
will converge to the true solution.
Thus we need a line of MATLAB code to
calculate the error at each iteration step
using code like
error(n+1) = x(n+1)-x(n)
. Insert this just before your
disp
command and modify the
disp
command so that it prints out
n+1
,
x(n+1)
and the error.
Record the value of the variable
error(21)
.