Dear students,
the first two lines of the MATLAB programs in the book (Figures 6.1.10,
6.2.11,
6.3.12, and 6.4.12) must actually be at the bottom of the main listing
given there...
the book is wrong...
For Euler here is what you do for the example in the book, FOR THE ASSIGNMENT
YOU WILL HAVE TO MAKE APPROPRIATE CHANGES...put the following in a file
named euler.m (to do this use an editor, e.g., notepad on Windoze or emacs
on Linux):
_____________________euler.m______________________
function [X,Y]=euler(x,y,x1,n)
h=(x1-x)/n;
X=x;
Y=y;
for i=1:n
y=y+h*f(x,y);
x=x+h;
X=[X;x];
Y=[Y;y];
end
function yp=f(x,y)
yp=x+y;
_____________________euler.m______________________
So, now you have file named euler.m and the matlab script above is in
it.
This file is (say) on your diskette, or on the hard disk.
Start matlab.
use the cd command (which means ``change directory'') to go to the directory
in the computer where the file is. You are still within matlab at the
>>
prompt.
Now, type
>> [X,Y]=euler(0,1,2,10)
This returns X, and the solution Y at each X. What you just typed passes
to
the script euler.m the values 0,1,2,10 which are X_o, Y_o, XFINAL,
N,
where XFINAL is the endpoint of the X-interval and N is the number
of
points so that the h (step size) in the script is what you actually
want it to be
(in this example h=0.2=(2-0)/10)).
To plot the solution just type
>> plot(X,Y)
You will have to find out how to print the graphs, and how to edit the
graphs
for axis labels, title, legends, etc.
To put more graphs on the same set of axis type:
>> hold on
This tells MATLAB to keep open the graph it just made. Typing again
>> [X,Y]=euler(0,1,2,20)
produces a new approximate solution with 1/2 the step size. Subsequently
>> plot(X,Y)
puts the new approximate solution graph, along with the previous one,
on the
same set of axis.
Repeating the process, allows you to put as many graphs as you want
on the
same set of axis.
You will have to do something similar for improved euler, and Runge-Kutta
too.
To graph the cumulative error for the example given above you must do
the
following (after each run of the euler script above):
>> YEX=2*exp(X)-X-1
This computes the exact solution at every point in the vector of values
X
and
puts it in the array YEX of same size
as X. Then, to plot the cumulative error
(instead of just the approximate solution) do:
>> plot(X,abs(Y-YEX))
Similarly for the assigned problem. The textbook script (Figure 6.2.11)
for the Improved Euler Method will have to be corrected similarly.