Professional Documents
Culture Documents
Dr Simon Fairfax
3 Plotting
Among MATLAB’s many strengths are its built-in plotting capabilities which allow us
to visualise results of our computations. There is a vast amount of built-in routines and
plotting functions which will produce very impressive graphical output. We start here
with the basics of 2-dimensional plots.
I The first command stores a vector x with entries 0.0, 2.5, 5.0, . . . , 47.5, 50.0.
I The vector x has 21 points or 20 equally spaced subintervals from 0 to 50.
I The second command plots vector x against the vector y which is computed through
a series of operations on x whilst working component-wise; see section on vectors.
I A Figure Window should pop up, displaying the graph on the right.
In the Figure Window, there are various tools and menu options for manipulating, saving
and printing the figure. For now, let us focus on the plot itself.
The function we are plotting should be smooth, yet our graph doesn’t look smooth. This
is because we only used 21 points on the interval of interest.
1
MATH111: Mathematical IT Skills
Dr Simon Fairfax
Suppose you plot this again, but use 1001 points on the interval. Also add the following
labelling lines before you have produced the new plot.
>> xlabel(’x’)
>> ylabel(’y’)
>> title(’y=xe^{-sin x}’)
Your improved figure, the contents of the Figure Window above, should look the same.
2
MATH111: Mathematical IT Skills
Dr Simon Fairfax
3.3 Multi-plots
For multiple plots on the same axes, the hold on command holds the current plot and
all axis properties, including the current color and linestyle, so that subsequent graphing
commands add to the existing graph without resetting the color and linestyle. Similarly,
the hold off command returns to the default mode
Example 3.2. Here’s a multi-plot in the Command window. We move to the next line,
without executing the command prematurely, by using Shift+Enter. Note, in the future
almost all of our plots will be done in the Editor window due to increased flexibility.
>> hold on
x=linspace(0,10,1001);
plot(x,sin(x),’rd--’)
plot(x,cos(x))
xlabel(’x’)
ylabel(’y’)
hold off
3
MATH111: Mathematical IT Skills
Dr Simon Fairfax
>> x=linspace(0,10,1001);
plot(x,sin(x))
plot(x,log(x))
produces a sketch of y = log(x) only, whereas the following code produces both.
>> figure(1)
plot(x,sin(x))
figure(2)
plot(x,log(x))