Matlab Array and Matrix
Manipulations and Graphics
Dr. Antonio A. Trani
Dept. of Civil and Environmental Engineering
Virginia Tech (A.A. Trani)
Objectives of the Handout
• To illustrate examples of matrix manipulation in
MATLAB
• To learn some of the basic plotting functions in
MATLAB
• Just for the fun of learning something new (the
most important reason)
Virginia Tech (A.A. Trani) 2
Basic Matrix Manipulation
• Matlab basic rules are derived from Linear Algebra
Virginia Tech (A.A. Trani) 3
Example # 1: Solution of Linear Equations
• Linear equations are important in many engineering
problems (optimization, structures, transportation,
construction, etc.)
Virginia Tech (A.A. Trani) 4
Example # 1: Solution of Linear Equations
“Backslash”
operator
Virginia Tech (A.A. Trani) 5
Example # 1: Solution of Linear Equations
Virginia Tech (A.A. Trani) 6
Array vs. Matrix Operations
• MATLAB differentiates between array and matrix operations
• Matrix operations apply to matrices using Linear Algebra
rules (hence also called Scalar operations)
• An example of this is solving a set of linear equations as
shown in the previous example
• Array operations apply when you want to do element by
element calculations on a multi-dimensional array
• An example of this is calculating the deflection of a
cantilever beam problem as shown next
Virginia Tech (A.A. Trani) 7
Examples of Matrix Operations
Let matrix A = [3 3 3 ; 2 2 2; 1 1 1] and B = [3 4 5]’
Valid matrix operations are:
c=A^2
d=A*A
e = A *B
f=A*3
g=A+5
Virginia Tech (A.A. Trani) 8
Array Operations Nomenclature
• Array operators have a period in front of the operand
(e.g., .*)
• For example: Creates a vector x with
x = 0:0.05:8; cell values from
0 to 8 at steps 0.05
y = sin(x^2)*exp(-x);
• Will not execute correctly because the manipulation of
array x requires a period in front of the * and ^ operands
• The following statements will work:
x = 0:0.05:8;
y = sin(x.^2).*exp(-x);
Note the (.) in front
of the operands
Virginia Tech (A.A. Trani) 9
Example # 2 : Cantilever Beam
Calculations
• A cantilever beam with a uniformly varying load is shown below
• We would create a simple Matlab script to estimate the beam
deflection for any station (x) along the beam
• The formula to estimate the deflection is:
Virginia Tech (A.A. Trani) 10
Example # 2 : Cantilever Beam
Calculations (cont.)
y = deflection of the beam at station x (m)
E = Young's modulus (N/m 2 )
I = bean moment of inertia (m 4 )
x = beam station (m)
Virginia Tech (A.A. Trani) 11
Example # 2 : Cantilever Beam Matlab Script
Virginia Tech (A.A. Trani) 12
Example # 2 : Cantilever Beam
Matlab Script (cont.)
Note the use of (.) in front
of the operands
Ellipses is used in
Matlab to indicate
a continuation statement
Virginia Tech (A.A. Trani) 13
Example # 2 : Cantilever Beam
Output Plot (beam deflection)
Steel beam
E = 200 GPa
(200 e9 N/m2)
Virginia Tech (A.A. Trani) 14
Observations
• A vector x is defined using the “linspace” function (linearly
spaced vector) (see line 25 above)
• linspace (starting point, ending point, no. of points)
• Since x is a vector with 100 elements, vector y (deflection) is
automatically set by Matlab to have 100 elements
• The period before * and ^ operands is needed to tell Matlab to
do element by element computations while calculating y
Virginia Tech (A.A. Trani) 15
Array Operators
Operation MATLAB Operators
Array multiplication .*
Array power .^
Left array division .\
Right array division ./
Matrix multiplication *
Matrix power ^
Matrix division /
Left matrix division \
Use these to do basic operations on arrays of any size
Virginia Polytechnic Institute and State University 16
Array Manipulation Tips
Always define the size of the arrays to be used in the
program (static allocation)
• Define arrays with zero elements (defines statically array
sizes and thus reduces computation time)
»d=zeros(1,3)
d=
0 0 0
»c=ones(1,3)
c=
1 1 1
Virginia Polytechnic Institute and State University 17
Array Manipulation Tips
Sample of for-loop without array pre allocation
Example:
tic;
for i=[Link];
d(i) = sin(i) ;
end
t=toc;
disp(['Time to compute array ', num2str(t), ' (seconds)'])
Time to compute array 5.2982 (seconds)
Times calculated using a Mac Book Air (10.8.5 OS and i7 Processor)
Virginia Polytechnic Institute and State University 17
Array Pre allocation
Array pre allocation saves time because MATLAB does
not have to dynamically change the size of each array as
the code executes
d=zeros(1,10e6); % pre allocates a vector with zeros
tic;
for i=[Link];
d(i) = sin(i) ;
end
t=toc;
disp(['Time to compute array ', num2str(t), ' (seconds)'])
Time to compute array 1.395 (seconds)
Times calculated using a Mac Book Air (10.8.5 OS and i7 Processor)
Virginia Polytechnic Institute and State University 18
Vector Operations in MATLAB
The following script is equivalent to that shown in the
previous page.
tic;
i=[Link];
d = sin(i);
t=toc;
disp(['Time to compute array ', num2str(t), ' (seconds)'])
Time to compute array 0.90465 (seconds)
Note: MATLAB vector operations are optimized to the
point that even compiling this function in C/C++ offers
little speed advantage (10-15%).
Times calculated using a Mac Book Air (10.8.5 OS and i7 Processor)
Virginia Polytechnic Institute and State University 19
Comparison of Results
The following table summarizes the array manipulation
results
CPU Timea
Procedure Ratiob
(seconds)
Standard for-loop 5.29820 1.00
Array 1.39500 1.54
Pre allocation
Vectorization 0.90465 5.85
a. Times calculated using a Mac Book Air (10.8.5 OS and i7 Processor)
b. Higher ratio means faster execution times
Virginia Polytechnic Institute and State University 20
Vectorization Issues
• To illustrate with a numerical example instances
where vectorization is not possible unless the
problem is partitioned into two sub-problems
• Problem partitioning to speed up computations
Virginia Tech (A.A. Trani) 20a
Example # 3: Beam Problem
• Consider the following beam loading condition
Virginia Tech (A.A. Trani)
20b
Observations
• The beam deflection and moment formulas change as
the station changes from left to right (i.e., x< a or x> a)
• Handling two distinct formulas requires a branching
statement (like an IF statement in the computations)
Virginia Tech (A.A. Trani)
20c
Matlab Script (with Branching)
Virginia Tech (A.A. Trani)
20d
Matlab Script (Branching - cont.)
Virginia Tech (A.A. Trani)
20e
Example # 3 : Beam Deflection
Steel beam
E = 2e6 psi
Virginia Tech (A.A. Trani)
20f
Graphs in MATLAB
There are many ways to build plots in MATLAB. Two of
the most popular procedures are:
1) Using built-in MATLAB two and three dimensional
graphing commands
2) Use the MATLAB Handle Graphics (object-oriented)
procedures to modify properties of every object of a
graph
Handle Graphics is a fairly advanced topic that is also
used to create Graphic User Interfaces (GUI) in
MATLAB. For now, we turn our attention to using
Matlab built-in two and three graphics.
Virginia Polytechnic Institute and State University 21
Plots Using Built-in Functions
MATLAB can generally handle most types of 2D and 3D
plots without knowing Handle Graphics
• ‘plot’ command for 2D plots
• ‘plot3d’ for 3D plots
• Use ‘hold’ command to superimpose plots interactively
or when calling functions
• Use the ‘zoom’ function to dynamically resize the screen
to new [x,y] limits
• Use the ‘subplot’ function to plot several graphs in one
screen
Virginia Polytechnic Institute and State University 22
Basic Plots in MATLAB
Two-dimensional line plots are easy to implement in
MATLAB
% Sample line plot
x=0:0.05:5;
y=sin(x.^1.8);
plot(x,y); % plot command
xlabel(‘x’) % builds the x label
ylabel(‘y’) % builds the y label
title(‘A simple plot’) % adds a title
grid % adds hor. and vert.
% grids
Try this out now.
Virginia Polytechnic Institute and State University 23
Other Types of 2-D Plots
bar bar plot
fplot simple plot of one variable (x)
semilogx and semilogy semilog plots
loglog logarithmic plot
polar polar coordinates plot
plotyy dual dependent variable plot
errorbar error bar plot
hist histogram plot
Virginia Polytechnic Institute and State University 24
More 2D Plots
stem generates stems at each data point
stairs discrete line plot (horizontal lines)
comet simple animation plot
contour plots the contours of a 2D function
quiver plots fields of a function
Virginia Polytechnic Institute and State University 25
Sample 2D Plots (semilog plot)
x=0:0.05:5;
y=exp(-x.^2);
semilogy(x,y); grid
10 0
10 -2
10 -4
10 -6
10 -8
10 -10
10 -12
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Virginia Polytechnic Institute and State University 26
Sample 2D Plots (loglog plot)
x=0:0.05:5;
y=exp(-x.^2);
loglog(x,y); grid
10 0
10 -1 -3
10 10 -2 10 -1 10 0
Virginia Polytechnic Institute and State University 27
Sample 2D Plots (bar plot)
x = -2.9:0.2:2.9;
bar(x,exp(-x.*x));
grid
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
0
-3 -2 -1 0 1 2 3
Virginia Polytechnic Institute and State University 28
Sample 2D Plots (stairs plot)
x=0:0.05:8;
stairs(x,sin(x.^2).*exp(-x));
grid
0.35
0.3
0.25
0.2
0.15
0.1
0.05
-0.05
-0.1
-0.15
0 1 2 3 4 5 6 7 8
Virginia Polytechnic Institute and State University 29
Sample 2D Plots (errorbar plot)
x=-2:0.1:2;
y=erf(x);
e = rand(size(x))/2; errorbar(x,y,e); grid
1.5
0.5
-0.5
-1
-1.5
-2.5 -2 -1.5 -1 -0.5 0 0.5 1 1.5 2 2.5
Virginia Polytechnic Institute and State University 30
Sample 2D Plots (polar plot)
% Polar plot
t=0:.01:2*pi;
polar(t,sin(2*t).*cos(2*t));
90
0.5
120 60
0.375
150 0.25 30
0.125
180 0
210 330
240 300
270
Virginia Polytechnic Institute and State University 31
Sample 2D Plots (stem plot)
x = 0:0.1:4;
y = sin(x.^2).*exp(-x);
stem(x,y); grid
0.35
0.3
0.25
0.2
0.15
0.1
0.05
-0.05
-0.1
-0.15
0 0.5 1 1.5 2 2.5 3 3.5 4
Virginia Polytechnic Institute and State University 32
Sample 2D Plots (Histogram)
x=randn(1,1000);
hist(x);
grid
300
250
200
150
100
50
0
-4 -3 -2 -1 0 1 2 3 4
Virginia Polytechnic Institute and State University 33
Sample 2D Plots (plotyy)
x=-2:0.1:2; y1=erf(x);
y2=erf(1.35.*x);
plotyy(x,y,x,y2);grid
0.5 1
0 0
-0.5 -1
-2 -1.5 -1 -0.5 0 0.5 1 1.5 2
Virginia Polytechnic Institute and State University 34
Sample 2D Plot (pie plot)
In this example we demonstrate the use of the gtext
function to write a string at the location of the mouse
acft = char('A310','A330','MD11','DC-10', 'L1011',...
'B747','B767','B777');
numbers=[12 15 24 35 16 120 456 156];
pie(numbers)
for i=1:8 % array of strings
gtext(acft(i,:)); % get text from char variable
end
title('Aircraft Performing N. Atlantic Crossings')
Virginia Polytechnic Institute and State University 35
Resulting Pie Plot
Aircraft Performing N. Atlantic Crossings
DC-10
MD11 L1011
3% 2% 1% B747
A330
A310 4% 19%
2%
B777
14%
55%
B767
Virginia Polytechnic Institute and State University 36
Quiver Plot
The quiver plot is good to represent vector fields.
In the example below a quiver plot shows the gradient of
a function called ‘peaks’
t=-3:.1:3;
[x,y]=meshgrid(t,t);
z= 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
[dx,dy]=gradient(z,.2,.2);
quiver(x,y,dx,dy,3)
Note: ‘peaks’ is a built-in MATLAB function
Virginia Polytechnic Institute and State University 37
Quiver Plot of ‘Peaks’ Function
3
-1
-2
-3
-4
-4 -3 -2 -1 0 1 2 3 4
Virginia Polytechnic Institute and State University 38
3D Representation of the Peaks Function
Peaks
-2
-4
-6
3
2
3
1 2
0 1
-1 0
-1
-2 -2
y -3 -3
x
Virginia Polytechnic Institute and State University 39
2D Plots (Contour Plot)
The following script generates a contour plot of the peaks
function
t=-3:.1:3;
[x,y]=meshgrid(t,t);
z= 3*(1-x).^2.*exp(-(x.^2) - (y+1).^2) ...
- 10*(x/5 - x.^3 - y.^5).*exp(-x.^2-y.^2) ...
- 1/3*exp(-(x+1).^2 - y.^2);
colormap(lines)
contour(x,y,z,15) % 15 contours are generated
grid
Virginia Polytechnic Institute and State University 40
Resulting Contour Plot of the ‘Peaks’ Function
3
-1
-2
-3
-3 -2 -1 0 1 2 3
Virginia Polytechnic Institute and State University 41
Sample 2D Plots (comet plot)
• Useful to animate a trajectory
• Try the following script
% illustration of comet plot
x = 0:0.05:8;
y = sin(x.^2).*exp(-x);
comet(x,y)
Virginia Polytechnic Institute and State University 42
Handling Complex 2-D Plots
Tampa Bay
Atlantic Ocean
Aircraft Tracks
Miami Intl. Airport
Gulf of México
-84 -83 -82 -81 -80 -79 -78 -77
Longitude (deg.)
Plot containing 830 flight tracks arriving or departing Miami Airport
Each track has 325 data points
Source: FAA, plot by A. Trani (Air Transportation Systems Lab)
Virginia Polytechnic Institute and State University 43
Zooming Into Previous Plot
Arrivals
Departures
Miami Intl. Airport
-81 -80.8 -80.6 -80.4 -80.2 -80 -79.8
Longitude (deg.)
Plot containing 830 flight tracks arriving or departing Miami Airport
Each track has 325 data points
Source: FAA, plot by A. Trani (Air Transportation Systems Lab)
Virginia Polytechnic Institute and State University 44
Sample Use of Subplot Function
Used the subplot function to display various graphs on the
same screen
% Demo of subplot function
x = 0:0.1:4;
y = sin(x.^2).*exp(-x);
z=gradient(y,.1) % takes the gradient of y every
% 0.1 units
subplot(2,1,1) % generates the top plot
plot(x,y); grid
subplot(2,1,2) % generates the lower plot
plot(x,z); grid
Virginia Polytechnic Institute and State University 45
Resulting Subplot
0.6
0.4
0.2
-0.2
0 0.5 1 1.5 2 2.5 3 3.5 4
0.5
-0.5
-1
0 0.5 1 1.5 2 2.5 3 3.5 4
Virginia Polytechnic Institute and State University 46
Sample Plot Commands
Standard 2D plot using the ‘subplot’ function
Latitude (deg) 40
35
30
25
-130 -120 -110 -100 -90 -80 -70 -60
Longitude (deg)
Occupancy of Sector 15 : OCF
12
10
Traffic (acft)
0
1100 1120 1140 1160 1180 1200 1220 1240 1260 1280 1300
Reference Time (min)
Plot containing 104 flight tracks crossing an airspace sector in Florida
Source: FAA, plot by A. Trani (Air Transportation Systems Lab)
Virginia Polytechnic Institute and State University 47
Zoom Command
The ‘zoom’
31
command is used to examine a smaller area
Latitude (deg)
30
29
28
27
-90 -88 -86 -84 -82 -80 -78 -76
Longitude (deg)
Occupancy of Sector 15 : OCF
12
10
Traffic (acft)
0
1100 1120 1140 1160 1180 1200 1220 1240 1260 1280 1300
Reference Time (min)
Plot containing 104 flight tracks crossing an airspace sector in Florida
Source: FAA, plot by A. Trani (Air Transportation Systems Lab)
Virginia Polytechnic Institute and State University 48
3-D Graphing in MATLAB
• A 3-D plot could help you visualize complex information
• 3D animations can be generated from static 3D plots
• 3D controls fall into the following categories:
- viewing control (azimuth and elevation)
- color control (color maps)
- lighting control (specular, diffuse, material, etc.)
- axis control
- camera control
- graph annotation control
- printing control
Virginia Polytechnic Institute and State University 49
Viewing Control
• 3D plots have two viewing angles than can be controlled
with the command view
- azimuth
- elevation
Example use: view(azimuth, elevation)
• Default viewing controls are: -37.5 degrees in azimuth
and 30 degrees in elevation
• Try the traffic file changing a few times the viewing
angle
Virginia Polytechnic Institute and State University 50
Rotating Interactively a 3D Plot
• Use the rotate3d command to view interactively the 3D
plots (good for quantitative data analysis)
• The zoom command does not work in 3D
>> plot3d(x,y,z)
>> rotate3d
>>
• Try rotating the traffic characteristics file using rotate3d
Retrieve the data file called: traffic flow data from our syllabus web site
Virginia Polytechnic Institute and State University 51
Sample 3D Plot (plot3 function)
plot3(density,speed,volume,'*')
3500
3000
2500
Volume (veh/hr)
2000
1500
1000 TextEnd
500
0
80
60 150
40 100
20 50
0 0
Density (veh/la-km) Speed (km/hr)
Virginia Polytechnic Institute and State University 52
Rotate Command
The rotate3d command is useful to visualize 3D data
interactively
3500
3000
2500
Volume (veh/hr)
2000
1500
1000
TextEnd
500
0
80
60
40
20 140
120
100
80
Density (veh/la-km) 60
0 40
20
0
Speed (km/hr)
Virginia Polytechnic Institute and State University 53
Sample 3D Graphics (mesh)
% Mesh Plot of Peaks
z=peaks(50);
mesh(z);
10
-5
-10
50
40 50
30 40
20 30
20
10 10
0 0
Virginia Polytechnic Institute and State University 54
Sample 3D Graphics (surf)
z=peaks(25);
surf(z);
colormap(jet); ;
8
-2
-4
-6
-8
25
20 25
15 20
10 15
10
5 5
0 0
Virginia Polytechnic Institute and State University 55
Sample 3D Graphics (surfl)
z=peaks(25);
surfl(z);
shading interp; colormap(jet);;
8
-2
-4
-6
-8
25
20 25
15 20
10 15
10
5 5
0 0
Virginia Polytechnic Institute and State University 56
Sample 3D Graphics (slice)
Slice 3D plots visualize the internal structure of set of
numbers as gradients
[x,y,z] = meshgrid(-2:.2:2,-2:.2:2,-2:.2:2);
v = x .* exp(-x.^2 - y.^2 - z.^2);
slice(v,[5 15 21],21,[1 10])
axis([0 21 0 21 0 21]);
colormap(jet)
Virginia Polytechnic Institute and State University 57
Slice Plot of Pseudo-Gaussian Function
20
15
10
0
20
15 20
15
10
10
5
5
0 0
Virginia Polytechnic Institute and State University 58
Sample 3D Graphics (stem3)
stem3 - plots stems in three dimensions as shown below
3500
3000
2500
Volume (veh/hr)
2000
1500
1000
TextEnd
500
0
80
60 150
40 100
20 50
0 0
Density (veh/la-km) Speed (km/hr)
Virginia Polytechnic Institute and State University 59