0% found this document useful (0 votes)
42 views

MATLAB: How Do You Work With Data To Solve Problems?

MATLAB is a tool for technical computing that allows users to work with data and solve problems. It integrates computation, visualization, and programming capabilities to express problems and solutions using familiar mathematical notation. MATLAB contains toolboxes for tasks like signal processing, image analysis, and control design. It allows users to quickly develop algorithms and obtain numerical solutions to complex problems using matrices and vectors without extensive programming. Some key capabilities include solving systems of linear equations, visualizing data, and performing numeric computation on matrix expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

MATLAB: How Do You Work With Data To Solve Problems?

MATLAB is a tool for technical computing that allows users to work with data and solve problems. It integrates computation, visualization, and programming capabilities to express problems and solutions using familiar mathematical notation. MATLAB contains toolboxes for tasks like signal processing, image analysis, and control design. It allows users to quickly develop algorithms and obtain numerical solutions to complex problems using matrices and vectors without extensive programming. Some key capabilities include solving systems of linear equations, visualizing data, and performing numeric computation on matrix expressions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 75

MATLAB: How do you work with

data to solve problems?


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.
“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
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
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
Signal & Image Processing
Signal Processing
Math and Analysis
Image Processing
Optimization
Communications
Requirements Management Interface
Frequency Domain System Identification
Statistics
Higher-Order Spectral Analysis
Neural Network
System Identification
Symbolic/Extended Math
Wavelet
Partial Differential Equations
Filter Design
PLS Toolbox
Mapping
Control Design
Spline
Control System
Fuzzy Logic
Data Acquisition and Import
Robust Control
Data Acquisition
μ-Analysis and Synthesis
Instrument Control
Model Predictive Control
Excel Link
Portable Graph Object
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 topic-
related MATLAB functions that extend the core
functionality significantly
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’)
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.
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
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
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”)
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
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
…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
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 no declarations needed
ans =
40

>> product = 16 * 23.24 mixed data types


product =
371.84
semi-colon suppresses output of the
>> product = 16 *555.24; calculation’s result
>> product
product =
8883.8
Variable Basics
>> clear clear removes all variables;
>> product = 2 * 3^3;
>> comp_sum = (2 + 3i) + (2 - 3i); clear x y removes only x and y
>> show_i = i^2;
complex numbers (i or j) require no
>> save three_things
special handling
>> clear
>> load three_things
>> who
save/load are used to
Your variables are:
comp_sum product show_i retain/restore workspace variables
>> product
product =
54
use home to clear screen and put cursor
>> show_i
at the top of the screen
show_i =
-1
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
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 : Matrix:
>> a=[1 2 3]; >> A=[1 2; 3 4];
>> a' >> A'
1 ans =
2 1 3
3 2 4
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 100.0000
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.
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
Matrices Operations

Given A and B:

Addition Subtraction Product Transpose


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]; But:
>> B=[5 6;7 8]; >> A.*B
>> A*B 5 12
19 22 21 32
43 50
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

b = x .* y c=x./y d = x .^2
x = A(1,:) y = A(3 ,:)
b= c= d=
x= y= 3 8 -3 0.33 0.5 -3 1 4 9
1 2 3 3 4 -1
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
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
Indexing Matrices
Given the matrix: A = n
0.9501 0.6068 0.4231
m
0.2311 0.4860 0.2774
Then:
A(1,2) = 0.6068

A(:,1) = [0.9501

0.2311 ]
1:m
A(1,2:3)=[0.6068 0.4231]
Adding Elements to a Vector or a Matrix
>> A=1:3 >> C=[1 2; 3 4]
A= C=
1 2 3 1 2
>> A(4:6)=5:2:9 3 4
A= >> C(3,:)=[5 6];
1 2 3 5 7 9 C=
1 2
>> B=1:2 3 4
B= 5 6
1 2
>> B(5)=7; >> D=linspace(4,12,3);
B= >> E=[C D’]
1 2 0 0 7 E=
1 2 4
3 4 8
5 6 12
Flow Control
• if
• for
• while
• break
• ….
Control Structures
Some Dummy Examples
• If Statement Syntax if ((a>3) & (b==5))
Some MATLAB Commands;
if (Condition_1) end

MATLAB Commands if (a<3)


elseif (Condition_2) Some MATLAB Commands;
elseif (b~=5)
MATLAB Commands Some MATLAB Commands;
elseif (Condition_3) end
MATLAB Commands if (a<3)
else Some MATLAB Commands;
else
MATLAB Commands Some MATLAB Commands;
end end

38
Control Structures
Some Dummy Examples
• For loop syntax for i=1:100
Some MATLAB Commands;
end

for i=Index_Array for j=1:3:200


Some MATLAB Commands;
MATLAB Commands end

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
Control Structures
• While Loop Syntax

Dummy Example
while (condition)
while ((a>3) & (b==5))
MATLAB Commands Some MATLAB Commands;
end
end
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.
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.
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
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
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.
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')
A graphics window showing a plot.
Some MATLAB plotting commands
Multiple Graphs

t = 0:pi/100:2*pi;
y1=sin(t);
y2=sin(t+pi/2);
plot(t,y1,t,y2)
grid on
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)
Graph Functions (summary)
• plot linear plot
• stem discrete plot
• grid add grid lines
• xlabel add X-axis label
• ylabel add Y-axis label
• title add graph title
• subplot divide figure window
• figure create new figure window
• pause wait for user response
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
Getting Help From MATLAB:
The Function Browser after plot has been selected

1-35
The MATLAB Help Browser

1-36
The Help Navigator

1-37
Useful Commands

• The three commands used most by MATLAB


users are
>>help functionname

>>lookfor keyword

>>demos
Random Numbers

x=rand(100,1);
stem(x);

hist(x,100)
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
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
Sum of Two Dies
• Simulate 10000 observations of the sum of
two fair dies
6 . . . . . .
5 . . . . . .
(1,6) (2,6) (3,6) (4,6) (5,6) (6,6)

4 . . . . . .
(1,5) (2,5) (3,5) (4,5) (5,5) (6,5)

3 . . . . . .
(1,4) (2,4) (3,4) (4,4) (5,4) (6,4)

2 . . . . . .
(1,3) (2,3) (3,3) (4,3) (5,3) (6,3)

1 . . . . . .
(1,2) (2,2) (3,2) (4,2) (5,2) (6,2)

(1,1) (2,1) (3,1) (4,1) (5,1) (6,1)

1 2 3 4 5 6
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 p[2]=0.0278
sum(y==3)/10000 ans = 0.0554 p[3]=0.0556
sum(y==4)/10000 ans = 0.0841 p[4]=0.0833
sum(y==5)/10000 ans = 0.1082 p[5]=0.1111
sum(y==6)/10000 ans = 0.1397 p[6]=0.1389
sum(y==7)/10000 ans = 0.1705 p[7]=0.1667
sum(y==8)/10000 ans = 0.1407 p[8]=0.1389
sum(y==9)/10000 ans = 0.1095 p[9]=0.1111
sum(y==10)/10000 ans = 0.0794 p[10]=0.0833
sum(y==11)/10000 ans = 0.0585 p[11]=0.0556
sum(y==12)/10000 ans = 0.0265 p[12]=0.0278
Sum of Two Dies

for i=2:12
z(i)=sum(y==i)/10000
end
bar(z)
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.
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.
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 time-
series for each column
of the data matrix
Average of the Data:
1
Applying the mean function >> mean(rpm_raw)
to the data matrix yields the
mean of each column ans =
1081.4 1082.8
1002.7
2
But you can easily compute
the mean of the entire matrix >> mean(mean(rpm_raw))
(applying a function to either
a single row or a single
column results in the function ans =
applied to the column, or the 1055.6
row, i.e., in both cases, the
application is to the vector).
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.


But we can apply the mean function
Example: If X = [0 1 2 along any dimension
3 4 5]

then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1


>> mean(rpm_raw, 2) 4]
ans = 3
1045.7
1064.7 So we can easily obtain the row
1060.7 means
1055
1045
max and its Index
1 MAX Largest component. 2
For vectors, MAX(X) is the largest
element in X. For matrices, MAX(X) >> max(rpm_raw)
is a row vector containing the ans =
maximum element from each column. 1115 1120 1043
For N-D arrays, MAX(X) operates
along the first non-singleton
dimension. >> max(max(rpm_raw))
ans =
[Y,I] = MAX(X) returns the indices 1120
of the maximum values in vector I.
If the values along the first non-
singleton dimension contain more >> [y,i] = max(rpm_raw)
than one maximal element, the index y =
of the first one is returned. 1115 1120 1043
i =
We can compute the 8 2 17
max of the entire matrix,
max along the columns
or of any dimension
min
>> min(rpm_raw) min along each column
ans =
1053 1053 961

>> min(min(rpm_raw)) min of entire matrix


ans =
961

>> [y,i] = min(rpm_raw)


y =
1053 1053 961
i =
22 1 22
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
Steps in engineering problem solving
The end

You might also like