MATLAB: How do you work with
data to solve problems?
Fall 2012
Lecture # XX
1
Mathematical Tools for Quantitative Methods
•
•
•
•
In today’s technology world, every engineering and computer science
discipline uses computers:
– For computer scientists, as an aid in writing programs.
– For engineers, as a tool to help in the design process, and also to help
in solving complex equations.
In most scientific and engineering disciplines, the most useful
mathematical equations normally do not have closed solutions.
– Often, useful equations are non-linear, perhaps involving second-order
differential equations, for which there is no general solution.
This means that many equations are solved using a numerical approach (a
fancy way of saying that answers are tried until one works!).
For modern technologists, there are many useful computer tools, normally
programs that aid in solving complex equations.
2
“Too many tools & too little time”
• In a course such as ECS 1200, we simply do
not have the time to examine many of the
available tools.
• However, there is one tool, readily
available, that would be useful to all
undergraduates in ECS that we can survey
briefly.
• MATLAB
3
So What Is MATLAB?
• A high-performance tool for technical
computing, integrating computation,
visualization, and programming in such a way
that problems and solutions are expressed in
familiar mathematical notation.
• an “interactive, matrix-based system for
algorithm development, GUI Design, data
analysis, data visualization, and numeric
computation”
• A recommended mathematical tool at UTD
– Available at the UTD Tech Store
4
What is MATLAB?
• MATLAB is an abbreviation for MATrix LABoratory
• MATLAB is basically a high level language which
has many specialized toolboxes for making things
easier for us as engineers and computer scientists
• How high?
MATLAB
High Level
Languages such as
C, Pascal etc.
Assembly
Why Use MATLAB?
• Used mainly for algorithm development and data
visualization
– Algorithms can be implemented and tested more
quickly and easily than with traditional programming
languages
• Quickly get numerical and graphic answers to matrix and
vector related math problems
• A way to solve complex numerical problems without
actually writing a program
– Built-in tools
– No complex programming knowledge needed
• MATLAB focuses on ease of use and quick development
6
Some of MATLAB’s Toolboxes
Math and Analysis
Optimization
Requirements Management Interface
Statistics
Neural Network
Symbolic/Extended Math
Partial Differential Equations
PLS Toolbox
Mapping
Spline
Data Acquisition and Import
Data Acquisition
Instrument Control
Excel Link
Portable Graph Object
Signal & Image Processing
Signal Processing
Image Processing
Communications
Frequency Domain System Identification
Higher-Order Spectral Analysis
System Identification
Wavelet
Filter Design
Control Design
Control System
Fuzzy Logic
Robust Control
μ-Analysis and Synthesis
Model Predictive Control
7
MATLAB’s Appeal
• Interactive code development proceeds
incrementally; excellent development and rapid
prototyping environment
• Basic data element is the auto-indexed array
• This allows quick solutions to problems that can be
formulated in vector or matrix form
• Powerful GUI tools
• Large collection of toolboxes: collections of topicrelated MATLAB functions that extend the core
functionality significantly
8
MATLAB Example 1
• MATLAB can easily solve families of linear
equations.
• For example, suppose you need to solve three linear
equations for x, y, and z such that:
2x+3y+z=11
x+y+z=6
4x-3y+z=1
• The MATLAB command to solve the equations
would be:
>> [x,y,z]=solve('2*x+3*y+z=11','x+y+z=6','4*x-3*y+z=1')
9
MATLAB Example 2
• An even tougher set of equations – say, five linear
equations, would be even easier, compared to
manual solution:
2v+2w+2x+2y+2z=30
2v+2w+2x+y-z=19
4x+y-z=3
v+w+x-y-z=5
5v-w+2x+2y+2z=27
• The same “solve” function is used. Equations are
written as before, using “*” to denote
multiplication, quotes (‘’) to denote the range of
each equation, and a comma separator.
10
MATLAB Summary
• MATLAB is a complex program that is an excellent
mathematical tool for solving complex science and
engineering problems.
• In general, it is so complex that it takes some “getting
used to.” You cannot just plunge into it today and
expect to be a master in about ten minutes.
• However, with a little work, you can master its
intricacies and become a MATLAB master.
• Because the student price is so good, and because
you will be using MATLAB in some of your advanced
UG courses, it would be a good idea to start learning
11
now!
MATLAB Screen
Command Window
type commands
Current Directory
View folders and m-files
Workspace
View program variables
Double click on a variable
to see it in the Array Editor
Command History
view past commands
save a whole session
using diary
12
Some MATLAB Development Windows
• Command Window: where you enter commands
• Command History: running history of commands which
is preserved across MATLAB sessions
• Current directory: current location for session
• Workspace: GUI for viewing, loading and saving
MATLAB variables
• Array Editor: GUI for viewing and/or modifying contents
of MATLAB variables (openvar varname or double-click
the array’s name in the Workspace)
• Editor/Debugger: text editor, debugger; editor works
with file types in addition to .m (MATLAB “m-files”)
13
Entering Commands and Expressions
• MATLAB retains your previous keystrokes.
• Use the up-arrow key to scroll back back through
the commands.
• Press the key once to see the previous entry, and
so on.
• Use the down-arrow key to scroll forward. Edit a
line using the left- and right-arrow keys the
Backspace key, and the Delete key.
• Press the Enter key to execute the command.
A video introduction:
• A Five Minute
Introduction to MATLAB
15
Example Session
>> 8/10
ans =
0.8000
>> 5*ans
ans =
4
>> r=8/10
r =
0.8000
>> r
r =
0.8000
>> s=20*r
s =
16
More Examples
>> 8 + 3*5
ans =
23
>> 8 + (3*5)
ans =
23
>>(8 + 3)*5
ans =
55
>>4^2128/4*2
ans =
0
>>4^212 8/(4*2)
ans =
3
17
…and some more examples
>> 3*4^2 + 5
ans =
53
>>(3*4)^2 + 5
ans =
149
>>27^(1/3) + 32^(0.2)
ans =
5
>>27^(1/3) + 32^0.2
ans =
5
>>27^1/3 + 32^0.2
ans =
11
18
19
20
Variables
• No need for types. i.e.,
int a;
double b;
float c;
• All variables are created with double precision
unless specified and they are matrices.
Example:
>>x=5;
>>x1=2;
• After these statements, the variables are 1x1
matrices with double precision
Variable Basics
>> 16 + 24
ans =
40
>> product = 16 * 23.24
product =
371.84
>> product = 16 *555.24;
>> product
product =
8883.8
no declarations needed
mixed data types
semi-colon suppresses output of the
calculation’s result
22
Variable Basics
>> clear
>> product = 2 * 3^3;
>> comp_sum = (2 + 3i) + (2 - 3i);
>> show_i = i^2;
>> save three_things
>> clear
>> load three_things
>> who
Your variables are:
comp_sum product show_i
>> product
product =
54
>> show_i
show_i =
-1
clear removes all variables;
clear x y removes only x and y
complex numbers (i or j) require no
special handling
save/load are used to
retain/restore workspace variables
use home to clear screen and put cursor
at the top of the screen
23
Special variables and constants
Numeric display formats
24
Matrices & Vectors
• All (almost) entities in MATLAB are matrices
• Easy to define:
• Use ‘,’ or ‘ ’ to separate row elements -- use
‘;’ to separate rows
>> A = [16 3; 5 10]
A =
16
3
5
10
25
Creating Vectors and Matrices
• Define
>> A = [16 3; 5 10]
A =
16
3
5
10
>> B = [3 4 5
6 7 8]
B = 3 4 5
6 7 8
• Transpose
Vector :
>> a=[1 2 3];
>> a'
1
2
3
Matrix:
>> A=[1 2; 3 4];
>> A'
ans =
1
3
2
4
26
Creating Vectors
Create vector with equally spaced intervals
>> x=0:0.5:pi
x =
0 0.5000 1.0000 1.5000 2.0000 2.5000 3.0000
Create vector with n equally spaced intervals
>> x=linspace(0, pi, 7)
x =
0 0.5236 1.0472 1.5708 2.0944 2.6180 3.1416
Equal spaced intervals in logarithm space
>> x=logspace(1,2,7)
x =
10.0000 14.6780 21.5443 … 68.1292
Note: MATLAB uses pi to represent
unit
100.0000
imaginary
, uses i or j to represent
27
Creating Matrices
•
•
•
•
•
•
zeros(m, n): matrix with all zeros
ones(m, n): matrix with all ones.
eye(m, n): the identity matrix
rand(m, n): uniformly distributed random
randn(m, n): normally distributed random
magic(m): square matrix whose elements
have the same sum, along the row, column and
diagonal.
• pascal(m) : Pascal matrix.
28
Matrix operations
•
•
•
•
^: exponentiation
*: multiplication
/: division
\: left division. The operation A\B is
effectively the same as INV(A)*B, although
left division is calculated differently and is much
quicker.
• +: addition
• -: subtraction
29
Matrices Operations
Given A and B:
Addition
Subtraction
Product
Transpose
30
Array Operations
• Evaluated element by element
.' : array transpose (non-conjugated
transpose)
.^ : array power
.* : array multiplication
./ : array division
• Very different from Matrix operations
>> A=[1 2;3 4];
>> B=[5 6;7 8];
>> A*B
19
22
43
50
But:
>> A.*B
5
21
12
32
31
The use of “.” – “Element” Operation
A = [1 2 3; 5 1 4; 3 2 1]
A=
1 2 3
5 1 4
3 2 -1
x = A(1,:)
x=
c=x./y
d = x .^2
b=
c=
0.33 0.5 -3
d=
y = A(3 ,:)
y=
1 2 3
b = x .* y
3 8 -3
3 4 -1
32
1
4
9
Some Built-in functions
•
•
•
•
•
•
•
•
•
•
•
mean(A):mean value of a vector
max(A), min (A): maximum and minimum.
sum(A): summation.
sort(A): sorted vector
median(A): median value
std(A): standard deviation.
det(A) : determinant of a square matrix
dot(a,b): dot product of two vectors
Cross(a,b): cross product of two vectors
Inv(A): Inverse of a matrix A
length(A): number of values in an array
33
Operators (relational, logical)
•
•
•
•
•
•
•
•
== Equal to
~= Not equal to
< Strictly smaller
> Strictly greater
<= Smaller than or equal to
>= Greater than equal to
& And operator
| Or operator
34
Indexing Matrices
Given the matrix:
n
A =
m
Then:
0.9501
0.2311
0.6068
0.4860
A(1,2) = 0.6068
A(:,1) = [0.9501
1:m
0.2311 ]
A(1,2:3)=[0.6068
0.4231]
35
0.4231
0.2774
Adding Elements to a Vector or a Matrix
>> A=1:3
A=
1 2 3
>> A(4:6)=5:2:9
A=
1 2 3 5 7
>> B=1:2
B=
1 2
>> B(5)=7;
B=
1 2 0
0
7
9
>> C=[1 2; 3 4]
C=
1 2
3 4
>> C(3,:)=[5 6];
C=
1 2
3 4
5 6
>> D=linspace(4,12,3);
>> E=[C D’]
E=
1 2 4
3 4 8
5 6 12
36
Flow Control
•
•
•
•
•
if
for
while
break
….
37
Control Structures
Some Dummy Examples
• If Statement Syntax
if (Condition_1)
MATLAB Commands
elseif (Condition_2)
MATLAB Commands
elseif (Condition_3)
MATLAB Commands
else
MATLAB Commands
end
if ((a>3) & (b==5))
Some MATLAB Commands;
end
if (a<3)
Some MATLAB Commands;
elseif (b~=5)
Some MATLAB Commands;
end
if (a<3)
Some MATLAB Commands;
else
Some MATLAB Commands;
end
38
Control Structures
Some Dummy Examples
• For loop syntax
for i=Index_Array
MATLAB Commands
end
for i=1:100
Some MATLAB Commands;
end
for j=1:3:200
Some MATLAB Commands;
end
for m=13:-0.2:-21
Some MATLAB Commands;
end
for k=[0.1 0.3 -13 12 7 -9.3]
Some MATLAB Commands;
end
39
Control Structures
• While Loop Syntax
while (condition)
MATLAB Commands
end
Dummy Example
while ((a>3) & (b==5))
Some MATLAB Commands;
end
40
You can perform operations in MATLAB in two
ways:
1. In the interactive mode, in which all
commands are entered directly in the
Command window, or
2. By running a MATLAB program stored in
script file. This type of file contains
MATLAB commands, so running it is
equivalent to typing all the commands—
one at a time—at the Command window
prompt. You can run the file by typing its
name at the Command window prompt.
41
Scripts and Functions
• Scripts do not accept input arguments, nor do they
produce output arguments. Scripts are simply MATLAB
commands written into a file. They operate on the
existing workspace.
• Functions accept input arguments and produce output
variables. All internal variables are local to the function
and commands operate on the function workspace.
• A file containing a script or function is called an m-file
• If duplicate functions (names) exist, the first in the
search path (from path command) is executed.
42
Use of M-File
Click to create
a new M-File
• Extension “.m”
• A text file containing script or function or program to run
43
Save file as Denem430.m
Use of M-File
If you include “;” at the
end of each statement,
result will not be shown
immediately
44
Writing User Defined Functions
• Functions are m-files which can be executed by
specifying some inputs and supply some desired
outputs.
• The code telling the MATLAB that an m-file is actually
a function is
function out1=functionname(in1)
function out1=functionname(in1,in2,in3)
function [out1,out2]=functionname(in1,in2)
• You should write this command at the beginning of
the m-file and you should save the m-file with a file
name same as the function name
45
Writing User Defined Functions
• Examples
– Write a function : out=squarer (A, ind)
• Which takes the square of the input matrix if the
input indicator is equal to 1
• And takes the element by element square of the
input matrix if the input indicator is equal to 2
Same Name
46
Writing User Defined Functions
•
Another function which takes an input array and returns the sum and product of its
elements as outputs
•
The function sumprod(.) can be called from command window or an m-file as
47
Keep in mind when using script files:
1. The name of a script file must begin with
a letter, and may include digits and the
underscore character, up to 63
characters.
2. Do not give a script file the same name
as a variable.
3. Do not give a script file the same name
as a MATLAB command or function. You
can check to see if a command, function
or file name already exists by using the
exist command.
48
MATLAB Graphics
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
xlabel('x = 0:2\pi')
ylabel('Sine of x')
title('Plot of the
Sine Function')
49
A graphics window showing a plot.
50
Some MATLAB plotting commands
51
Multiple Graphs
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
52
Multiple Plots
t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
subplot(2,2,1)
plot(t,y1)
subplot(2,2,2)
plot(t,y2)
53
Graph Functions (summary)
•
•
•
•
•
•
•
•
•
plot
stem
grid
xlabel
ylabel
title
subplot
figure
pause
linear plot
discrete plot
add grid lines
add X-axis label
add Y-axis label
add graph title
divide figure window
create new figure window
wait for user response
54
Notes:
• “%” is the neglect sign for MATLAB
(equaivalent of “//” in C). Anything after it on
the same line is neglected by MATLAB
compiler.
• Sometimes slowing down the execution is
done deliberately for observation purposes.
You can use the command “pause” for this
purpose
pause %wait until any key
pause(3) %wait 3 seconds
55
Getting Help From MATLAB:
The Function Browser after plot has been selected
1-35
56
The MATLAB Help Browser
1-36
57
The Help Navigator
1-37
58
Useful Commands
• The three commands used most by MATLAB
users are
>>help functionname
>>lookfor keyword
>>demos
59
Random Numbers
x=rand(100,1);
stem(x);
hist(x,100)
60
Coin Tosses
• Simulate the outcomes of 100 fair coin tosses
x=rand(100,1);
p=sum(x<0.5)/100
p =
0.5400
• Simulate the outcomes of 1000 fair coin tosses
x=rand(1000,1);
p=sum(x<0.5)/1000
p =
0.5110
61
Coin Tosses
• Simulate the outcomes of 1000 biased coin
tosses with p[Head]=0.4
x=rand(1000,1);
p=sum(x<0.4)/1000
p =
0.4160
62
Sum of Two Dies
• Simulate 10000 observations of the sum of
two fair dies
6
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
1
2
3
4
5
6
(1,6) (2,6) (3,6) (4,6) (5,6) (6,6)
5
(1,5) (2,5) (3,5) (4,5) (5,5) (6,5)
4
(1,4) (2,4) (3,4) (4,4) (5,4) (6,4)
3
(1,3) (2,3) (3,3) (4,3) (5,3) (6,3)
2
(1,2) (2,2) (3,2) (4,2) (5,2) (6,2)
1
(1,1) (2,1) (3,1) (4,1) (5,1) (6,1)
63
Sum of Two Dies
• Simulate 10000 observations of the sum of two
fair dies
x1=floor(6*rand(10000,1)+1);
x2=floor(6*rand(10000,1)+1);
y=x1+x2;
sum(y==2)/10000
ans = 0.0275
sum(y==3)/10000
ans = 0.0554
sum(y==4)/10000
ans = 0.0841
sum(y==5)/10000
ans = 0.1082
sum(y==6)/10000
ans = 0.1397
sum(y==7)/10000
ans = 0.1705
sum(y==8)/10000
ans = 0.1407
sum(y==9)/10000
ans = 0.1095
sum(y==10)/10000
ans = 0.0794
sum(y==11)/10000
ans = 0.0585
sum(y==12)/10000
ans = 0.0265
p[2]=0.0278
p[3]=0.0556
p[4]=0.0833
p[5]=0.1111
p[6]=0.1389
p[7]=0.1667
p[8]=0.1389
p[9]=0.1111
p[10]=0.0833
64 p[11]=0.0556
p[12]=0.0278
Sum of Two Dies
for i=2:12
z(i)=sum(y==i)/10000
end
bar(z)
65
Basic Data Analysis
• Basic, and more advanced, statistical analysis is
easily accomplished in MATLAB.
• Remember that the MATLAB default is to assume
vectors are columnar.
• Each column is a variable, and each row is an
observation.
66
Vibration Sensors Data
Each column is
the raw rpm
sensor data from
a different sensor
used in an
instrumented
engine test. The
rows represent
the times
readings were
made.
67
Plotting the Data
>>
>>
>>
>>
plot(rpm_raw)
xlabel('sample number - during time slice');
ylabel('Unfiltered RPM Data');
title(‘3 sequences of samples from RPM sensor’)
Note that in this case
the plot command
generates one timeseries for each column
of the data matrix
68
Average of the Data:
1
Applying the mean function
to the data matrix yields the
mean of each column
2
But you can easily compute
the mean of the entire matrix
(applying a function to either
a single row or a single
column results in the function
applied to the column, or the
row, i.e., in both cases, the
application is to the vector).
>> mean(rpm_raw)
ans =
1081.4
1002.7
1082.8
>> mean(mean(rpm_raw))
ans =
1055.6
69
The mean Function
>> help mean
MEAN
Average or mean value.
For vectors, MEAN(X) is the mean value of the elements in X. For
matrices, MEAN(X) is a row vector containing the mean value of
each column. For N-D arrays, MEAN(X) is the mean value of the
elements along the first non-singleton dimension of X.
MEAN(X,DIM) takes the mean along the dimension DIM of X.
Example: If X = [0 1 2
3 4 5]
then mean(X,1)
>> mean(rpm_raw,
ans =
1045.7
1064.7
1060.7
1055
1045
But we can apply the mean function
along any dimension
is [1.5 2.5 3.5] and mean(X,2) is [1
2)
4]
3
So we can easily obtain the row
means
70
max and its Index
1
MAX
Largest component.
For vectors, MAX(X) is the largest
element in X. For matrices, MAX(X)
is a row vector containing the
maximum element from each column.
For N-D arrays, MAX(X) operates
along the first non-singleton
dimension.
[Y,I] = MAX(X) returns the indices
of the maximum values in vector I.
If the values along the first nonsingleton dimension contain more
than one maximal element, the index
of the first one is returned.
We can compute the
max of the entire matrix,
or of any dimension
2
>> max(rpm_raw)
ans =
1115
1120
1043
>> max(max(rpm_raw))
ans =
1120
>> [y,i] = max(rpm_raw)
y =
1115
1120
1043
i =
8
2
17
max along the columns
71
min
>> min(rpm_raw)
ans =
1053
min along each column
1053
>> min(min(rpm_raw))
ans =
961
>> [y,i] = min(rpm_raw)
y =
1053
1053
i =
22
1
22
961
min of entire matrix
961
72
Standard Deviation, Median, Covariance
>> median(rpm_raw) % median along each column
ans =
1080
1083.5
1004
>> cov(rpm_raw) % covariance of the data
ans =
306.4
-34.76
32.192
-34.76
244.9
-165.21
32.192
-165.21
356.25
>> std(rpm_raw) % standard deviation along each
column
ans =
17.504
15.649
18.875
>> var(rpm_raw) % variance is the square of std
ans =
306.4
244.9
356.25
73
Steps in engineering problem solving
74
Homework #XX
• MATLAB tutorial
• Due XX
75
Tutorial
• http://www.mathworks.com/academia/stude
nt_center/tutorials/ml_onramp/player.html
76
77
Credits
• Introduction to MATLAB for Engineers by
William J. Palm III
• Dr Nathan Dodge, UTD Faculty
• www.mathworks.com
78
© Copyright 2026 Paperzz