Professional Documents
Culture Documents
Plotting: Programming With Matlab
Plotting: Programming With Matlab
Unit What
1 Introduction to MATLAB
2 Flow control & Data Structures
3 Plotting
4 Strings & File IO
5 Complex Numbers
6 Combinatorics
7 Linear Algebra
8 Statistics & Data Analysis
9 Polynomial Approximation,
Curve Fitting
10 Root Finding, Numerical
Differentiation
11 Numerical Integration
12 MATLAB GUI
2
REVIEW OF BASIC 2D PLOTS
3
WHAT IS A HANDLE?
4
QUIZ
5
SOLUTION
• If we want to plot f2, we simply plot x on one axis, and f2 on the other. There is no way to
calculate f2(100) as x stops at 10.
• If we want to plot f1, we will need to fish the function out of the MATLAB database. We use
the function handle for that. Than we can recalculate it again for any value of x.
6
SOLUTION
• Let’s define a function f in two different ways:
>> x=1:1:10
>> f1 = @(x) x.^2; % This is an Handle
>> f2 = x.^2; % This is a vector
>> x=1:1000:10000 % Redefinition of x
>> figure, plot (x,f2) % We just plot existing x and f
>> figure, plot (x,f1(x)) % We fish f1 out of dbase through
% its handle, and we recalculate it
Check Y axis: figure 1 is wrong as being f1 a vector its values were not recalculated
7
QUIZ (REPRISE)
8
OVERVIEW OF THE PROPERTY EDITOR
9
OBJECT PROPERTIES
• We already discussed that we don’t want to use GUIs: error prone, complicated,
and bad for documentation.
10
OBJECT HANDLES
• Now that we can identify all the objects in our plot we can easily modify their properties
without having to manually work with the Property Editor.
11
OBJECT PROPERTIES
• We can fetch any property of a graphics object using the get command:
• get(h) – returns all properties of the object identified by handle h.
• get(h, 'PropertyName') – returns the value of property
'PropertyName' of the object identified by handle h.
12
AXES LIMITS
• MATLAB automatically determines the range of the axes when a plot is created,
but the result is not always suitable.
• In our example, the curve is cut off at 2π but the x-axis (abscissa) ends at 7.
• We would like to modify the right limit of the x-axis to 2π while preserving the left
limit. We would also like more room at the top and bottom of the plot
• We use the get command to fetch the x-axis limits since we want to keep the left
limit determined automatically by MATLAB.
• The new x-axis range is [0, 2π] and the new y-axis range is [-1.2, 1.2].
13
AXES TICKS
• Another issue we had with the plot was the size of the number labels on the axes.
• A quick look at the properties list of the axes object shows several font-related
properties: FontName, FontSize, FontAngle, etc.
14
AXES TICKS WITH STRINGS
• Suppose we want to label the x-axis in radians using the “π” character.
• A simple way to accomplish this is by using the “\” symbol, which maps English letters to
Greek letters.
• Using this symbol, the characters “pi” corresponds to the character “π”
• This time, we must specify XTickLabel using a cell array of strings.
15
BUILT-IN AXIS MODES
16
LINE SPECIFICATION
• The line object create by the plot function can also be modified using the same
methods; for example, let’s make it a thick, green, dash-dot line.
• First, obtain a handle for the line object by giving an output to the plot command:
h = plot(x,y);
set(h, 'LineStyle', '-.', ...
'LineWidth', 7.0, ...
'Color', 'g')
17
MULTIPLE PLOTS
x = -10:0.1:10;
y1 = x.^2 - 8;
y2 = exp(x);
figure, plot(x,y1)
figure, plot(x,y2)
• A new figure window with default properties is created simply by calling figure.
• Be careful when formatting figure objects using the gcf handle, as it refers to the
most recently created figure object.
18
SUBPLOTS
subplot(2,2,1)
text(.3,.5, 'Subplot #1')
subplot(2,2,2)
text(.3,.5, 'Subplot #2')
subplot(2,2,3)
text(.3,.5, 'Subplot #3')
subplot(2,2,4)
text(.3,.5, 'Subplot #4')
19
SUBPLOTS
• If we want to have a plot that covers multiple subplot positions, we can make the
input p a vector that specifies these positions.
x = -5:0.1:5;
y1 = exp(x);
y2 = sqrt(abs(x));
y3 = sin(x)./x;
subplot(2,2,[1 3]), plot(x,y1)
subplot(2,2,2), plot(x,y2)
subplot(2,2,4), plot(x,y3)
20
OVERLAID PLOTS
• The command hold on retains the current figure as new graphs are added.
• hold off reverts this behavior; any subsequent calls to a plotting function will
overwrite the figure.
• Any of the graph’s properties can be modified as previously shown regardless of
the hold function; the previous formatting was applied to obtain the plot shown.
21
TITLES, AXIS LABELS, AND LEGENDS
• Titles, x-axis and y-axis labels, and legends can be easily added with their
respective commands: title, xlabel, ylabel, and legend.
• These functions only require a single input argument: a string of the label’s
contents.
• The remaining arguments can be 'PropertyName', PropertyValue, ... as
we’ve seen throughout this lecture to modify properties such as font size.
22
FIGURE SIZE
• Fortunately, we can modify the properties of our figure object to obtain the desired
results; there are three relevant properties:
• PaperPosition – a 4 element vector [left, bottom, width,
height] describing position and size of the figure in the context of a printed
page.
• PaperPositionMode – Allows two settings:
• manual uses the values specified by PaperPosition;
• auto uses the same size as it appears on the computer screen.
• PaperUnits – Units that define the PaperPosition property (inches by
default).
23
FIGURE SIZE
• The first line of code above returns a 4 element array figSize = [left,
bottom, width, height].
• left and bottom define the distance from the lower-left corner of the page to the
lower-left corner of the figure window; these are irrelevant here.
• In our example, we only want to change the width of the plot to make it wider.
• We add 3 inches to the current width and keep all other properties the same.
24
FILE FORMATS
• Figures can be saved in several formats; some of the more useful formats are:
• .fig – MATLAB figure file; useful for preserving all plot information, especially in
the case of future work.
• .bmp – Uncompressed image file.
• .jpeg – Compressed image file.
• .eps – Object-oriented image file; Scalable format.
• The most ideal format to save your plots for the purpose of presentation is .eps.
• Since it is object-oriented, rather than pixel-based, it is very tolerant to rescaling.
• Figures can be saved via code using either saveas or print functions:
25
GRAPH PRESENTATION
BAD BETTER
26
OTHER PLOTS & VISUALIZATIONS
• Thus far, we have only used 2-D line plots to demonstrate proper formatting.
• MATLAB has a wide variety of specialized plotting functions:
• plot3 – 3-D line plot.
• semilogx, semilogy, loglog – logarithmic plots.
• imagesc – visualize a matrix as an image.
• bar, hist – bar plots and histograms.
• mesh, surf – 3-D surface and mesh plots.
• polar – plot function in polar coordinates on a Cartesian plane.
• quiver – plot velocity vectors as arrows.
• stem – plot discrete data values as stems that extend from the x-axis.
• scatter – scatter plot.
• stairs – stairstep plot for piecewise constant functions.
• All of the concepts that we’ve previously learned can and should be applied to any
of these and all other types of plots.
27
QUIZ
>> X= -2:1:2
>> Y= -2:1:2 Z=X+Y
>> Z= X+Y
x,y −2 −1 0 1 2
A. No −2 −4 −3 −2 −1 0
B. Yes −1 −3 −2 −1 0 1
C. Yes, but does not do what we want! 0 −2 −1 0 1 2
1 −1 0 1 2 3
2 0 1 2 3 4
28
QUIZ
• We want to draw the function Z = F(x,y) = x+y with x and y = [−2, −1,0,1,2]
• Is the following a valid MATLAB code ?
>> X= -2:1:2
>> Y= -2:1:2
>> Z= X+Y
x,y −2 −1 0 1 2
A. No −2 −4 −3 −2 −1 0
B. Yes
−1 −3 −2 −1 0 1
C. Yes, but does not do what we want!:
0 −2 −1 0 1 2
Z = [−4 −2 0 2 4]
1 −1 0 1 2 3
We wanted a 2-dimensional function (matrix), 2 0 1 2 3 4
but we got a vector
29
2D FUNCTIONS
• If X and Y are vectors, the result of X+Y will be a vector whose entries are sums of
the corresponding values in X and Y
• If we want to obtain a matrix Z=X+X, we need to give MATLAB matrices X and Y as
input!
[X,Y] = meshgrid(-2:1:2);
Z = X + Y;
x −2 −1 0 1 2 y x,y −2 −1 0 1 2
−2 −1 0 1 2 −2 −2 −2 −2 −2 −2 −2 −4 −3 −2 −1 0
−2 −1 0 1 2 −1 −1 −1 −1 −1 −1 −1 −3 −2 −1 0 1
−2 −1 0 1 2
+ 0 0 0 0 0 0
= 0 −2 −1 0 1 2
−2 −1 0 1 2 1 1 1 1 1 1 1 −1 0 1 2 3
−2 −1 0 1 2 2 1 1 1 1 1 2 0 1 2 3 4
30
PLOTTING 3D SURFACES
2 +𝑦 2 )
• For example, plot the Gaussian function, 𝑓 ሺ𝑥, 𝑦ሻ = 𝑒 −(𝑥 .
[X,Y] = meshgrid(-2:0.1:2);
Z = exp(-X.^2 - Y.^2);
• The x and y coordinates of all points (x,y) of our domain are stored separately in
matrices X and Y, respectively.
• Using vector operations, we can calculate the height of our function at all points
(x,y) simulatenously and store the result in Z.
31
PLOTTING 3D SURFACES
Source www.mathworks.com
mesh(X,Y,Z)
figure
surf(X,Y,Z, ...
'FaceColor', 'interp', ...
'EdgeColor', 'none', ...
'FaceLighting', 'phong')
daspect([2 2 1])
axis tight
view(-50,30)
camlight left
32
PLOTTING 3D SURFACES
Source www.mathworks.com
33
BAR PLOTS
G = [46 38 29 24 13];
S = [29 27 17 26 8];
B = [29 23 19 32 7];
Source www.mathworks.com
34
BAR PLOTS
• This plot contains three bar objects, one for each set of medal data, G, S, and B.
• Thus, when we stored the handle h = bar(... we obtained a vector h, where h(1),
h(2), and h(3) identifies each respective bar object, G, S, and B.
%Change the face color the bars to match the medals (Red, green,
Blue)
set(h(1), 'FaceColor', [0.8 0.8 0])
set(h(2), 'FaceColor', [0.5 0.5 0.5])
set(h(3), 'FaceColor', [0.55 0.41 0.21])
Source www.mathworks.com
35
VISUALIZE DATA AS AN IMAGE
36
QUIZ
• A colormap is simply a 256x3 matrix that specifies 256 different RGB values from 0
to 1 to which elements of a matrix are mapped. The 1 st column represents red, the
2nd green, and the 3rd blue.
A. Map=[V’ V’ V’]
E. Map=[Z’ Z’ Z’];
3.5
1 2 3 4 5 6 7 8 9 10
37
QUIZ
• A colormap is simply a 256x3 matrix that specifies 256 different RGB values from 0
to 1 to which elements of a matrix are mapped. The 1 st column represents red, the
2nd green, and the 3rd blue.
38
VISUALIZE DATA AS AN IMAGE
• A colormap is simply a 256x3 matrix that specifies 256 different RGB values to
which elements of a matrix are mapped. T
0 1 254 255
• For example, colormap(gray) would look like:
0 1 … 254 255
• The first rows [0,0,0], [1,1,1], etc. represent
dark colors and are mapped to small values. 0 1 254 255
• The later rows represent bright colors and
are mapped to large values. T
0 0 0 0
• Let’s create a custom green colormap:
0 1 … 254 255
• The 1st column represents red, the
2nd green, and the 3rd blue. 0 0 0 0
imagesc(x) 1
1.5
map = zeros(256,3); 2
3
colormap(map) 3.5
1 2 3 4 5 6 7 8 9 10
39
STEM AND PIECEWISE PLOTS
• stem(x,y) plots the data y as a stem that extends to the x-axis. The values of y
are indicated by circles that terminate each stem.
figure
x = linspace(0, 4*pi, 40);
y = sin(x);
stairs(y)
figure
stem(y)
40