Plotting in Matlab
A.J. Melhus, 4-18-10; Revised by C. Chen, 2-17-12 Revised by H. Sheets, 3-21-13
The basic syntax is:
where x and y are vectors containing the data you wish to plot. x and y must have the same length.
To try, we should set up x and y first. Let's define a vector from 0 to 2pi, using the default stepsize of 1:
x1 = 0:2*pi
x1 = 0 1 2 3 4 5 6
Then we can assign values to y1 based on x1:
y1 = sin(x1)
y1 = 0 0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794
Then we can plot the sine function:
THIS PLOT LOOKS BAD because x1 only contains 7 points (we need more points to make a smooth graph).
Let's use linspace to make a much more smooth graph by creating a vector from 0 to 2pi containing 100 linearly spaced points:
x2 = linspace(0, 2*pi); y2 = sin(x2); plot(x2,y2)
THIS PLOT LOOKS GOOD because x2 contains many more points, creating a smoother graph. By default, linspace uses 100 points, but remember, if you give linspace a third argument, such as:
x3 = linspace(0,2*pi,50);
you can specify the number of points (such as 50) you want it to create.
(taken/edited from http://www.engin.umich.edu/group/ctm/extras/plot.html )
The color and point marker can be changed on a plot by adding a third parameter (in single quotes) to the plot command: plot(x,y, 'aesthetic')
- aesthetic consists of one to three characters which specify a color and/or point marker type - color and point marker types include:
For example, to plot y2 as a red, dotted line instead of the default blue straight line, the command should be changed to:
Whenever you make a plot, don't forget to properly label the x- and y-axis by using xlabel and ylabel:
plot(x2, y2) xlabel('variable x') ylabel('sin(x)')
Also, it's nice to give your plot a title so everyone can understand immediately what's the figure about:
Note that the title and axis labels will be erased when you call plot again without using hold on.