In this tutorial we will assume that you know how to create vectors and matrices, know how to index into them, and know about loops. For more information on those topics see one of our tutorials onvectors,matrices,vector operations, orloops.
In this tutorial we will introduce the basic operations for creating plots. To show how theplotcommand is used, an approximation using Euler's Method is found and the results plotted. We will approximate the solution to the D.E. y'= 1/y, y(0)=1. A step size of h=1/16 is specified and Euler's Method is used. Once done, the true solution is specified so that we can compare the approximation with the true value. (This example comes from the tutorial onloops.)
>> h = 1/16;
>> x = 0:h:1;
>> y = 0*x;
>> y(1) = 1;
>> for i=2:max(size(y)),
y(i) = y(i-1) + h/y(i-1);
>> true = sqrt(2*x+1);
Now, we have an approximation and the true solution. To compare the two, the true solution is plotted with the approximation plotted at the grid points as a green 'o'. Theplotcommand is used to generate plots in matlab. There is a wide variety of arguments that it will accept. Here we just want one plot, so we give it the range, the domain, and the format.
That's nice, but it would also be nice to plot the error:
Okay, let's print everything on one plot. To do this, you have to tell matlab that you want two plots in the picture. This is done with thesubplotcommand. Matlab can treat the window as an array of plots. Here we will have one row and two columns giving us two plots. In plot #1 the function is plotted, while in plot #2 the error is plotted.
The new approximation is plotted, but be careful! The vectors passed toplothave to match. The labels are given for the axis and a title is given to each plot in the following example. The following example was chosen to show how you can use thesubplotcommand to cycle through the plots at any time.
??? Error using ==> plot
Vectors must be the same lengths.
>> title('Errors for h=1/32')
>> title('Errors for h=1/16')
Figure 2.The errors for the two approximations
Finally, if you want to print the plot, you must first print the plot to a file. To print a postscript file of the current plot you can use theprintcommand. The following example creates a postscript file called error.ps which resides in the current directory. This new file (error.ps) can be printed from the UNIX prompt using the lpr command.