NoteSet_6_v1
NoteSet_6_v1
Section 0: Introduction
• We have gone through all of the “logical” aspects of this class, i.e., if, while,
and for.
• The most common (and argumentatively, most important) is the ability to plot
things in MATLAB.
o Note: this is VERY introductory. We are just seeing the tip of the
iceberg with this. There are so many plotting capabilities that we won’t
be able to cover. If you are ever struggling to plot something the way
you want, remind yourself: MATLAB can do it, it’s just a matter of
how. Google is your friend.
• Why do we plot?
o To convey information!
1
Dr. Brett Freidkes University of South Florida
▪ If you have data that you want to share, plots are typically the
best way of explaining that information to others. Quick,
informative, clear.
• Figure 1 shows some examples of different figure types (note that these are
from my graduate dissertation...the moral: plotting is used ALL THE TIME).
2
Dr. Brett Freidkes University of South Florida
• Before we jump into plotting, let’s discuss what a figure is and what a plot is.
o A figure is essentially the blank slate that we will be putting plots on.
o A plot is the data/function/etc. that we want to display.
• If you type the word figure into the Command Window (or in the Editor
Window), a blank figure will appear in a new window on screen.
3
Dr. Brett Freidkes University of South Florida
Figure 2: The blank figure panel that appears in a new window after typing figure into MATLAB.
o If we try to plot something, MATLAB will put that plot on the “active”
figure, which is the one that you clicked last.
o In Figure 3, we can see that Figure 2 is the active plot since on the top-
left corner of the window, its text is darker than the other figure (see the
content inside the blue boxes).
▪ Note that to avoid confusion, I will bold MATLAB figures and
leave the unbolded text referring to the figures in this specific
Note Set document.
4
Dr. Brett Freidkes University of South Florida
Figure 3: Two figure panels on screen at the same time. Note that Figure 2 is currently the "active" figure since its label is darker
than the label of Figure 1 (see the blue boxes).
• If you wanted to close a figure, you could x-out (of course), but you can also
type close into the Command Window.
o This will close the active figure.
• If you want to close ALL the figures, you can type close all and it will exit all
the open figure windows.
• If you want to copy/paste a figure, go to the menu options in the figure window
and go to:
o Edit → Copy Figure
o This command will take the figure exactly as it currently is and allow
you to paste it in other places.
▪ “Currently is” implies the size, formatting, etc. will be
copy/pasted.
• You can also save figures as .fig files if you go to:
o File → Save (or Save As...)
o The way that the figure currently is (i.e., formatting, size, etc.) will be
saved on your computer. You can then open that figure exactly as you
had left it.
5
Dr. Brett Freidkes University of South Florida
• The command plot will plot a series of points and connect the dots inside a
figure window.
o For example, imagine we want to plot a line that is composed of two
points: (0,2) and (1,3).
o The x-values are 0 and 1.
o The y-values are 2 and 3.
o The way that plot works is that you will provide it a vector (i.e., a one-
dimensional matrix) of x-values and a vector of y-values.
▪ The x-vector is inputted first and the y-vector is inputted second.
Figure 4: Plot containing points (0,2) and (1,3). A line is drawn between the two points.
• Important note: the points themselves aren’t plotted (meaning you can’t see
circles or anything). You only see the line connecting them.
o We will discuss how to do this later in this document.
6
Dr. Brett Freidkes University of South Florida
• Another note: you can write the matrix directly into the plot command as
shown below.
time 1 4 6 7 10
voltage -1 -4 10 4 1
• Using the plot command and assuming that time is on the x-axis (voltage is
on the y-axis), we will draw a line connecting the points. This is shown in
Figure 5.
Figure 5: Data seen in Table 1 plotted, i.e., (1,-1), (4, -4), (6, 10), (7,4), and (10,1)
• Note! The order that you organize the points in your vector MATTERS. Let’s
say we take the same data but we switch the 2nd and 3rd points (highlighted in
Table 2 below).
7
Dr. Brett Freidkes University of South Florida
o Figure 6 shows this. MATLAB does not make assumptions for what
you want, i.e., it does not assume you want a plot perfectly from
left-to-right.
Table 2: Data from an experiment.
time 1 6 4 7 10
voltage -1 10 -4 4 1
time = [1 6 4 7 10];
voltage = [-1 10 -4 4 1];
plot(time, voltage)
Figure 6: Same data from Table 1, but we flipped the 2nd and 3rd data point. MATLAB does not assume you want the plot to be
entirely from left-to-right.
x = 0:3:9; %[0 3 6 9]
8
Dr. Brett Freidkes University of South Florida
• To find our y-values at each of those points, we want to square each one
individually.
o The easiest way to do that is to use the dot operator, which will perform
element-by-element operations on a matrix.
x = 0:3:9; %[0 3 6 9]
y = x.^2 %dot operator to create [0 9 36 81]
• At this point, we have two vectors of equal length that can be plotted against
each other.
o If they weren’t equal length, MATLAB will give an error!
x = 0:3:9; %[0 3 6 9]
y = x.^2 %dot operator to create [0 9 36 81]
plot(x,y)
9
Dr. Brett Freidkes University of South Florida
• If we refine the x-vector so that it has more values, we can evaluate the graph
at more points and create a smoother curve. Figure 8 shows this.
Figure 8: Smoother graph since the x-vector increment was reduced from 3 to 0.01. More data points = smaller lines connecting
points = smoother curve.
Hold
• If you type hold on in the code, MATLAB knows to keep the previous data
set.
o If you type hold off, it will assume that you do NOT want the previous
data set in the figure.
10
Dr. Brett Freidkes University of South Florida
Figure 9: The red curve is the smoother data set from Figure 8, while the blue curve is the function only evaluated at 4 data
points. Using hold, we can compare them.
• Regarding the variables used above, we could easily change the variable
names to something like x1, y1, x2, and y2 to keep all the data as separate
terms.
o If you choose to recycle the same variables, the first plot remains
unaffected since it is ALREADY in the figure panel...we will just
overwrite the values of x and y in the Workspace.
11
Dr. Brett Freidkes University of South Florida
• In the code below, we will use a for loop to compare lines of different slopes
from x = 0 to x = 3.
o The variable x is defined before the loop and tells us which values on
the x-axis to evaluate the different functions at.
o The for loop cycles through slopes of 1:4
▪ So, on the first iteration of the loop, m (the slope) is 1.
▪ On the next iteration, m is 2
▪ And so on...
o Within a loop, we will find y, which will be the slope for that loop
iteration multiplied by the vector x.
▪ Note that y will be the same length as x
▪ We do not need a dot operator to multiply m and x since m is a
constant (only need the dot for multiplying matrices and doing
element-by-element operations).
o Because we wrote hold on, the graphs will be plotted on top of each
other.
Figure 10: Using a for loop to plot various curves on top of each other.
12
Dr. Brett Freidkes University of South Florida
x = 0:0.01:3; %x-values
▪ Let’s redo the same exact problem but using a different method for coding.
o This time, we defined a vector m before the for loop, m = [1 2 3 4].
o We will run the for loop for the correct number of times (since
1:length(m) is 1:4).
o Then, based on the value of ii, we will call the particular value of m out.
▪ For example, ii is initially 1 once the for loop starts, so m(1)
means the first element in the m vector (this happens to be equal
to 1).
▪ We multiply m(ii) by x to give y and plot
▪ Then, ii becomes 2 and we access m(ii) = m(2) (which happens
to be equal to 2).
▪ This continues for each element in the m matrix.
X = 0:0.01:3;
m = 1:4;
for ii = 1:length(m)
y = m(ii)*x; %this picks the iith element in the m vector
plot(x,y)
hold on
end
13
Dr. Brett Freidkes University of South Florida
x = 0:0.01:3;
m = [4 -1 2 3.5]; %length of 4
linspace
• Another list generator is linspace, which will create a list with “linear
spacing” between points.
o The difference between this and the colon operator is that we can set
how many points we want without specifying the increment. We need:
14
Dr. Brett Freidkes University of South Florida
• This will ensure that you have the specified number of points, where the
distance between points is constant.
o This specified number of points N includes the starting and ending
points.
o If the number of points is left blank, then MATLAB defaults to a value
of 100 (the fifth example in Table 3).
o Note that if the number of points desired is 1 (the last line in Table 3
below), MATLAB defaults that value to the ending point.
▪ If you type help linspace into the Command Window, you will
see the description and defaults of the table.
• Note: linspace and the colon operator basically do the same exact thing, just
in different ways.
Table 3: Examples of using linspace.
linspace(x1,x2,N) Output
linspace(0,1,2) [0 1]
linspace(0,1,3) [0 0.5 1]
linspace(0,1,4) [0 0.3333 0.6666 1]
linspace(10,20,6) [10 12 14 16 18 20]
linspace(1,100) [1 2 3...98 99 100]
linspace(0,150,1) 150
15
Dr. Brett Freidkes University of South Florida
Section 2: Customization
• We now have a general understanding of how to use the plot function. But the
previous examples in this document are not appealing to look at.
• This section discusses how to improve the graphs, both from a cosmetic
perspective and a technical one.
• First, Figure 13 shows the general layout of a figure. We will discuss how to
alter these items individually in the coming subsections.
Figure 13: A description of different parameters that change the look of your graph. Image taken from Kaw, Chapter 3.
16
Dr. Brett Freidkes University of South Florida
Figure 14: The figure from Example #1 with the appropriate axis labels now.
• To create labels, you simply type xlabel() and ylabel() with the text inside of
the command.
o Use single quotations (apostrophes) just like we do when we use disp
or fprintf.
• The code for plotting Figure 14 is shown below.
• What if we want to change the range of the axis numbers? For example,
instead of going from 1 to 10 on the x-axis, maybe I want to go from 2 to 6.
o Additionally, maybe I want to change the -4 to 10 on the y-axis to -3
to 8.
• This requires the xlim() and ylim() command, which is basically setting up
the lower and upper limits of the graph.
17
Dr. Brett Freidkes University of South Florida
Figure 15: Using xlim and ylim, we can change the upper/lower limits of each axis.
18
Dr. Brett Freidkes University of South Florida
• First, xticks and yticks both change the ticks that are visible on the graph.
o Figure 16 shows this based on the code below.
o Note that we removed the xlim and ylim commands added prior so we
can see all the data this time.
• Like most other things in MATLAB, this requires brackets within the
parentheses to group a list of numbers.
Figure 16: Using xticks([1 5 8 10]) and yticks([-4 0 4 10]), we create the plot above.
o With text, we will use curly brackets to enclose the group of custom
labels.
o These labels will correspond with the ticks that were specified on the
axis using the xticks and yticks commands earlier in the code.
Figure 17: Custom labels on the ticks using xticklabels and yticklabels.
• What about the font size of the axis, including the labels and the ticks?
o I typically make all my font sizes 14...just a recommendation.
• First, we can add other inputs into the xlabel and ylabel commands.
o We will separate using a comma and then use apostrophes to tell
MATLAB what we’re trying to alter. Then, provide the number so it
knows.
xlabel('Time, t [s]','fontsize',14)
ylabel('Voltage, V [volts]','fontsize',14)
20
Dr. Brett Freidkes University of South Florida
• Note that there are LOADS of properties you can change like this. MATLAB’s
documentation on their website discusses a lot of them, like changing the font
type, boldness, color, etc.
• The last one I want to discuss is changing properties of the graph coordinate
axes themselves.
o The axes themselves are referred to in MATLAB as gca (standing for
“graph coordinate axes”).
• A command like set() can change a property of the coordinate axes, like the
font size. Below is the command I most often use to get the graph looking
more appealing.
• Figure 18 shows the result of implementing these changes, where the font size
of the ticks, labels, etc. are much easier to read.
o Compare this figure to Figure 5...much better, no?
Figure 18: The graph after changing the label and gca sizes.
• This is straightforward...if you want to title your graph, you can use the
title() command and type the label that will go above the graph.
21
Dr. Brett Freidkes University of South Florida
o You can also use the same types of commands we did with the labels
described earlier.
• Now that we are done addressing the outer portions of the figure, let’s move
inwards. We will discuss:
o The data itself
o Legends
o Grids
• The general syntax for changing properties is to type the property of interest
and then the value/type for that property.
22
Dr. Brett Freidkes University of South Florida
o This is shown generally in Figure 20, where we will type the property
(examples: ‘LineStyle’, ‘MarkerSize’, ‘Color’, etc.) and then the
corresponding value for what we want.
o If this “value” is text (like what color we want), then we use single
apostrophes as well.
o If the “value” is a number, we just write the number without
apostrophes.
Figure 20: General format for accessing a property and then changing it to a specified value.
• Properties that you can change about the line you plot:
o Color
o Markers (and their properties)
o Line type and thickness
• If you want to change properties of a line that you plotted, you can do so in
the plot command itself.
o First, the color: we can do this in 3 different ways, all shown below.
o 1) Type the property ‘color’ after the x and y inputs. Then, type one of
the predefined colors in MATLAB (you can see these in Figure 21).
▪ Each predefined color has a letter associated with it as seen in
Figure 21...you can just type that as well.
o 2) You can remove the property title ‘color’ if you are using a
predefined color. Just include the color name immediately after the x
and y inputs.
23
Dr. Brett Freidkes University of South Florida
---------------------------------------------------------------------------------------------------
• Next, what are markers? Remember earlier when I said that we can only draw
lines when using the default plot function and not show the data points
themselves?
o Markers are those data points!
• The second column in Figure 21 shows different types of markers you can use
to represent your data points.
o This includes circles, stars, squares, etc.
x = 0:0.1:10;
y = sin(x);
plot(x, y, 'Marker','o') %using circles as markers
xlabel('x-axis','fontsize',14)
ylabel('y-axis','fontsize',14)
set(gca,'fontsize',14)
• If you don’t specify the property ‘Marker’ in the plot command, then
MATLAB will think you ONLY want the dots and no lines.
o Essentially, when editing the ‘Marker’ property, you are accessing the
properties of the marker on the line. If you don’t access the property
of the line, it will assume that there is no line.
o The case with just markers is
Figure 22: plot(x,y,'Marker','o') (left) versus plot(x,y,’o’) (right). There is no line connecting the dots in the right figure.
• Other properties that you can change about the markers besides which shape
they are include:
o The Marker Size
o The Marker Face Color
o The Marker Edge Color
• Figure 23 shows how changing the marker properties may change the
appearance of your graph.
25
Dr. Brett Freidkes University of South Florida
Figure 23: Different MarkerSize and MarkerFaceColor properties...not affiliated with the code above
• Below shows all three properties being changed in one line of code.
o We consistently list properties one after another.
o Note that the first property, the marker type, didn’t have the ‘Marker’
command before it like we discussed above (so we will have just
upwards arrows as the markers, no line).
• Figure 24 shows the output of the code below.
x = 0:0.1:10;
y = sin(x);
plot(x,y,'s','MarkerSize',10,'MarkerEdgeColor','r','MarkerFaceColor','g')
xlabel('Time, t [s]')
ylabel('Voltage, V [volts]')
set(gca,'fontsize',14)
--------------------------------------------------------------------------------------------------
26
Dr. Brett Freidkes University of South Florida
• The last property we need to investigate is the line style and width.
o The type of line corresponds with the third column in Figure 21.
o Like the other properties, we type the characteristic we want to
specify after the x and y inputs.
x = 0:0.1:10;
y = sqrt(x);
plot(x,y,'LineStyle','--') %dashed line
• The code above produces Figure 25, where the line is now dashed (see in
Figure 21 how the dashed line corresponds with the symbol -- ).
x = 0:0.1:10;
y = sqrt(x);
plot(x,y,'b','LineWidth',0.5)
hold on
plot(x,2*y,'r','LineWidth',2)
plot(x,3*y,'k','LineWidth',3.3)
xlabel('x')
ylabel('y')
set(gca,'fontsize',14) %set graph coordinate axes font to 14
27
Dr. Brett Freidkes University of South Florida
• You can also change the style of the line using the third column in Figure 21.
o Same procedure as before: we include the property after the x- and y-
inputs and then specify it to the value we want.
o This is exemplified below and in Figure 27.
x = 0:0.1:3;
y = exp(x);
plot(x,y,'k','LineStyle','--')
hold on
plot(x,2*y,'r','LineStyle',':')
plot(x,3*y,'b','LineStyle','-.')
set(gca,'fontsize',14)
28
Dr. Brett Freidkes University of South Florida
• The shorthand version of changing a line: you can change the three
properties in one command.
o Referencing Figure 21, properties include color, marker type, and line
style in that order (order of the columns).
o Since these are the most common to change, MATLAB allows you to
change them in one go.
o The code below shows an example that produces Figure 28.
x = 0:0.1:3;
y = log10(x); %log, base-10
plot(x,y,'rs--') %red, squares, dashed
hold on
plot(x,2*y,'b*:') %blue, stars, dotted
xlabel('x','fontsize',14)
ylabel('y','fontsize',14)
set(gca,'fontsize',14)
Figure 28: Comparing different colors, marker types, and line style in one command.
• Legends are important for distinguishing different data sets on the same
figure.
o The legend command allows you to type text in the order that the
plots are created.
o In the code below, we plot y1 first…that means that the first spot in
the legend will correspond with this graph (i.e., the style in the legend
matches the style in the figure).
29
Dr. Brett Freidkes University of South Florida
x = 0:0.01:8;
y1 = sin(x);
y2 = sin(x-pi/4);
plot(x,y1,'r','linewidth',2)
hold on
plot(x,y2,'b','linewidth',2)
xlabel('Time, t [s]','fontsize',14)
ylabel('Pressure, P [Pa]','fontsize',14)
set(gca,'fontsize',14)
legend('Sensor #1','Sensor #2','fontsize',14)
• Lastly, we could include a grid for reading convenience by just typing the
command grid on in the code. Below shows the same graph as above with a
grid.
30
Dr. Brett Freidkes University of South Florida
• There is the convenience of your code running and all the properties do
exactly what you want! That’s the benefit of having the commands above
known.
• However, if you are making a plot for a one-time purpose, you may want to
edit it accordingly. You can use the figure window itself to do this.
o At the top of the figure is an icon to open the Property Inspector (see
Figure 31).
31
Dr. Brett Freidkes University of South Florida
Section 3: Subplots
• There are instances where you may want two graphs to be plotted near each
other, but not on the same set of axes (because of varying units, for example).
• This is where the concept of subplot comes in.
• Figure 33 shows an example of a subplot, where 2 graphs are included.
o The top graph shows the height of a tree as a function of time.
o The bottom graph shows how many apples that tree produces as a
function of time.
o We can compare the two graphs and gain information about their
relationship (for example, when the tree is 30 years old, it’s above 100
inches tall and produces near 100 apples).
Figure 33: Subplot example, where we see two separate axes and two separate curves
32
Dr. Brett Freidkes University of South Florida
Figure 35: Subplot grid, where the numbers represent the graphs we may want to edit.
Example
• Let’s plot a function from 0 to 5 using 1000 points and the area under its
curve as a function of x.
o We will do a 2x1 subplot, where the top plot is the function and the
bottom is the integration.
𝑓(𝑥) = 𝑥 2
𝑥
1
𝑎𝑟𝑒𝑎 = ∫ 𝑥 2 𝑑𝑥 = 𝑥 3
0 3
33
Dr. Brett Freidkes University of South Florida
34
Dr. Brett Freidkes University of South Florida
Figure 37: After most recent code, we activated Graph #2 and plotted.
35
Dr. Brett Freidkes University of South Florida
36
Dr. Brett Freidkes University of South Florida
a) linspace(1,0.5,2)
b) linspace(1,3,2)
c) linspace(1,2,2)
d) linspace(1,2,3)
e) linspace(1,0.5,3)
3) What color would the plot be if the following code was used?
co = [0 1 0];
plot(x,y,'color',co)
a) Black
b) Green
c) Red
d) White
e) Blue
37
Dr. Brett Freidkes University of South Florida
4) How many data sets will be shown in the plot created from the code below?
x = 0:0.01:5;
y = x.^3+1;
plot(x,y)
plot(x,2*y)
hold on
plot(x,3*y)
hold off
plot(x,4*y)
plot(x,5*y)
a) 1
b) 2
c) 3
d) 4
e) 5
38
Dr. Brett Freidkes University of South Florida
a) linspace(1,0.5,2)
b) linspace(1,3,2)
c) linspace(1,2,2)
d) linspace(1,2,3)
e) linspace(1,2,0.5)
The command 1:0.5:2 will create a list that starts with 1, increments by 0.5, and
ends at 2. So the list is [1 1.5 2].
We have a list that starts at 1, ends at 2, and is 3 elements. Based on the format of
linspace (Figure 12), our answer is linspace(1,2,3). So, answer choice D.
The points that make up this plot are (1,2) and (5,6). Since the x-values are
combined in a vector and the y-values are combined in a separate vector, the
answer ends up being choice B.
39
Dr. Brett Freidkes University of South Florida
3) What color would the plot be if the following code was used?
co = [0 1 0];
plot(x,y,'color',co)
a) Black
b) Green
c) Red
d) White
e) Blue
The 3-element matrix corresponds with the colors red, green, and blue in that
order. Since the red and blue indices are 0 and the green is at a maximum of 1, the
graph will be green. Answer choice B.
4) How many data sets will be shown in the plot created from the code below?
x = 0:0.01:5;
y = x.^3+1;
plot(x,y)
plot(x,2*y)
hold on
plot(x,3*y)
hold off
plot(x,4*y)
plot(x,5*y)
a) 1
b) 2
c) 3
d) 4
e) 5
The first plot is created and immediately overwritten since hold wasn’t on. After
the 2nd plot, we hold the 3rd plot, so we currently have two data sheets on the same
figure. We turn hold off and plot the 4th function and then immediately overwrite it
with the 5th function. So at the end of the day, only 1 function is shown.
40