0% found this document useful (0 votes)
15 views135 pages

Matlab Overview

MATLAB is a high-level programming language and software environment designed for numerical computation, scientific calculations, and engineering applications. Originally developed in the 1970s to provide students access to linear algebra routines, it has evolved to include a wide range of features such as matrix manipulation, data visualization, and application development. MATLAB is widely used across various engineering fields for tasks including signal processing, image processing, and mathematical modeling.

Uploaded by

Pixel Aswath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views135 pages

Matlab Overview

MATLAB is a high-level programming language and software environment designed for numerical computation, scientific calculations, and engineering applications. Originally developed in the 1970s to provide students access to linear algebra routines, it has evolved to include a wide range of features such as matrix manipulation, data visualization, and application development. MATLAB is widely used across various engineering fields for tasks including signal processing, image processing, and mathematical modeling.

Uploaded by

Pixel Aswath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 135

MATLAB

What is MATLAB?
 MATLAB = Matrix (or) Mathwork Laboratory
 MATLAB is a High Level Language
 MATLAB is a software environment for interactive numerical computation
 MATLAB is a powerful general purpose system for doing Mathematics,
Scientific and Engineering calculations

Matlab

High Level
Languages such as
C, Pascal etc.

Assembly
MATLAB Background
 1970 – Cleve Moler, chairman of CS dept, at university of Mexico
• Designed to provide student access to LINPACK and EISPACK
without learning FORTRAN
 1984 – Jack Little joined Cleve and Steve Bangert found the
Mathwork and developed C rewrite of MATLAB
• Adopted by control design engineers, in education for teaching of
linear algebra and numerical analysis and for Scientist involved
with image processing
FORTRAN TO MATLAB

FORTRAN:
real*8 A(10,10), B(10,10), C(10,10)
do i=1,10
do j=1,10
C(i,j) = A(i,j) + B(i,j)
10 continue
20 continue

MATLAB:
C=A+B
LINPACK AND EISPACK

 LINPACK - Linear algebra subroutines for vector-matrix


operations, solving linear systems

 EISPACK - compute eigenvalues and eigenvectors of


matrices

Later on Matrix laboratory does matrix manipulation,


Programming, application development, GUI design,etc..
MATLAB Features
• Plot the results of certain basic arithmetic operations:
– addition, multiplication etc.
– exponential, logarithm etc.
– trigonometry, complex numbers.
• Working with arrays of numbers:
– straight line plots.
– operation on vectors.
– matrices, circles.
• Graph plots:
– Sine, cosine plots
– overlay plots.
• Programs to understand creation, saving, execution of files.
• Basic 2D and 3D plots:
– parametric space curve, polygons with vertices.
– 3D contour lines.
MATLAB Functions

Matrix computations and linear algebra


Solving nonlinear equations
Numerical solution of differential equations
Mathematical optimization
Statistics and data analysis
Signal processing
Modelling of dynamical systems
Solving partial differential equations
Simulation of engineering systems
How MATLAB Works?

MATLAB
Series of
Matlab
commands
Command
m-files mat-files
Line

functions
Input Command Data
Output execution like DOS storage/
capability command window loading
MATLAB System
MATLAB System consists of 5 main parts
• MATLAB Language
High level matrix or array language with control flow
statements
• MATLAB Working environment
Tools for developing, managing, debugging and profiling
m-files
• Handle Graphics
Includes 2D, 3D and GUI
• MATLAB Mathematical Function Libraries
Computation algorithms like sine, cosine, transforms,etc
• MATLAB Application Program Interface(API)
For reading and writing MAT files and for dynamic linking
APPLICATION
• Communication signals
• DC current analysis
• Image processing Application
• Engineering and scientific calculation
• Filtering
• Image Processing with GUI (Graphical User Interface)
Application
• Fuzzy Logic Applications
• Neural Network Applications
• Signal processing application
• Electrical Engineering simulation
• Control system application
MATLAB FOR ENGINEERS

• MATLAB are used in various engineering fields such as


– Biomedical Engineering – For Medical image processing, data
processing, signal processing
– Chemical engineering – For curve fitting, finding equilibrium,
conversation of mass, numerical computations,etc
– Aerospace engineering – Flow control, vector plots, matrix and
image visualization, data analysis, etc.
– Mechanical engineering – For heat transfer, thermodynamics,
fluid mechanisms, dynamics, etc
– Electrical engineering – Numeric analysis of circuit,
Transmission lines, Control system modelling, matrix
computation, etc
– Communication engineering – Image processing, signal
processing, process of modulation and demodulation
FEATURES

• High-level language for numerical computation, visualization, and


application development
• Interactive environment for iterative exploration, design, and problem
solving
• Mathematical functions for linear algebra, statistics, Fourier analysis,
filtering, optimization, numerical integration, and solving ordinary
differential equations
• Built-in graphics for visualizing data and tools for creating custom
plots
• Development tools for improving code quality and maintainability
and maximizing performance
• Tools for building applications with custom graphical interfaces
• Functions for integrating MATLAB based algorithms with external
applications and languages such as C, Java, .NET, and
Microsoft® Excel®
MATLAB WORKSPACE
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 NAMES
• Variable names are Case Sensitive

• Variable names can contain up to 63 characters (as of


MATLAB 6.5 and newer)

• Variable names must start with a letter followed by


letters, digits, and underscores.

• All variables are shown with


>> who
>> whos

• Variables can be stored on file


>> save filename
>> clear
>> load filename
SPECIAL VARIABLES

ans Default variable name for results


pi Value of 
inf infinite
NaN Not a number e.g. 0/0
i and j i = j =
eps Smallest incremental number
realmin The smallest usable positive real number
realmax The largest usable positive real number
CLEARING OPERATIONS
• Clear
Remove items from workspace, freeing up system memory
Example: Clear a single variable
a = 1;
b = 2;
clear a
whos
Clear specific variables by name
clear -regexp ^Mon ^Tue ^Wed;//regular
expression
Clear all compiled scripts, functions and MEX function
clear functions
• Clearvars
Clear variables from memory
Example: Clear named variables
a = 1;
b = 2;
c = 3;
clearvars a c

Clear all variables except specified


clearvars -except C D
Clear global variables except specified
clearvars -global -except x*
Arrays Introduction

• In MATLAB, all variables of all data types are


multidimensional arrays.
• A vector is a one-dimensional array
• A matrix is a two-dimensional array
• a vector x = [1 2 5 1]

x=
1 2 5 1

• a matrix x = [1 2 3; 5 1 4; 3 2 -1]

x=
1 2 3
5 1 4
3 2 -1

• transpose y = x’ y=
1
2
5
1
Long array
• t =1:10

t=
1 2 3 4 5 6 7 8 9 10

• k =2:-0.5:-1

k=
2 1.5 1 0.5 0 -0.5 -1

• B = [1:4; 5:8]

x=
1 2 3 4
5 6 7 8
Cell arrays
Cells: Initialization
Function Purpose
length Length of vector or largest array dimension
ndims Number of array dimensions
numel Number of array elements
size Array dimensions
iscolumn Determine whether input is column vector
isempty Determine whether array is empty
ismatrix Determine whether input is matrix
isrow Determine whether input is row vector
isscalar Determine whether input is scalar
isvector Determine whether input is vector
blkdiag Construct block diagonal matrix from input arguments
circshift Shift array circularly
ctranspose Complex conjugate transpose
diag Diagonal matrices and diagonals of matrix
flipdim Flip array along specified dimension
fliplr Flip matrix left to right
flipud Flip matrix up to down
ipermute Inverse permute dimensions of N-D array
permute Rearrange dimensions of N-D array
repmat Replicate and tile array
reshape Reshape array
rot90 Rotate matrix 90 degrees
shiftdim Shift dimensions
issorted Determine whether set elements are in sorted order
sort Sort array elements in ascending or descending order
sortrows Sort rows in ascending order
squeeze Remove singleton dimensions
transpose Transpose
vectorize Vectorize expression
MATLAB FILE TYPES
Associate Files
File Result
Extension
.fig Opens file in figure window
.m Opens file in Editor
.mat Opens Import Wizard to load the data into the MATLAB
workspace.
.slx, .mdl Opens file in a Simulink® model window
.mex[a] Displays icon for MATLAB in Windows Explorer tool
.p Displays icon for MATLAB in Windows Explorer tool
[a]
MEX-file extensions are platform-specific. See Using MEX-Files.
To associate a different file type with MATLAB, use the Windows Default
Programs control panel. On Windows 7 systems:

1.Click the Windows Start menu.


2.Select Control Panel.
3.Select Programs.
4.Select Default Programs.
5.Select Associate a file type or protocol with a program.
6.In the Set Associations window, find the file extension in the displayed list
and double-click it
7.To change the default association, click Change Program. The Open
with dialog box opens, which lists other programs that might be
recommended for this file extension. If it is a file extension associated with
MATLAB, such as .mat, the list includes all the versions of MATLAB you
have installed.
8.Click OK in the Open With dialog box.
9.To close the Set Associations window, click Close.
Supported file types
• MATLAB formatted data -MAT
• Text -TXT
• Spreadsheet -XLS,XLSM
• Extensible Markup Language -XML
• Data Acquisition toolbox -DAQ
• Scientific data -CDF
• Image -BMP, GIF, JPEG, TIF
• Audio - MP3, WAV, M4A
• Video - MPG,MP4, M4V,MOV
Some Useful MATLAB commands

what List all m-files in current directory


dir List all files in current directory
ls Same as dir
type test Display test.m in command window
delete test Delete test.m
cd a: Change directory to a:
chdir a: Same as cd
pwd Show current directory
which test Display current directory path to test.m
MATRICES
Matrix operation
• + addition
• - subtraction
• * multiplication
• ^ power
• ‘ transpose for a real matrix and complex –conjugate transpose
for a complex matrix (transpose for a complex matrix is .’)
• \ left division, / division
x = A \ b is the solution of A * x = b
x = b / A is the solution of x * A = b
Matrix math
– Dimensions must agree
Scalar math
– Same as usual
Scalar / matrix math
– Scalar + matrix = [scalar + matrix(i, j)]
– Scalar * matrix = [scalar * matrix(i, j)]
To make the ‘*’ , ‘^’, ‘\’ and ‘/’ entry-wise, we precede the operators by ‘.’

a .* b multiplies each element of a by the respective element of b

a ./ b divides each element of a by the respective element of b

a .\ b divides each element of b by the respective element of a

a .^ b raise each element of a by the respective b element


Example
– x = [1 2 3]; y = [4 5 6];
– x ‘* y = 32
– x .* y = [4 10 18]
• diag: Diagonal matrices or diagonals of a matrix.
diag(A) for matrix A is the diagonals of A.
A= 0.1531 0.4929 0.1478
0.0495 0.6107 0.4326
0.9340 0.1224 0.7917
Then diag(A)= [ 0.1531; 0.6107; 0.7917]

• blockdiag: Construct a block diagonal matrix

blockdiag(A,B,C)=
Matrix Manipulation
• MATLAB treats all variables as matrices.
• Vectors are special forms of matrices and contain only one row OR one
column.
• Scalars are matrices with only one row AND one column

Vectors (arrays) are defined as


>> v = [1, 2, 4, 5]
>> w = [1; 2; 4; 5]

Matrices (2D arrays) defined similarly


>> A = [1,2,3;4,-5,6;5,-6,7]
Matrix Index
• The matrix indices begin from 1 (not 0 (as in C))
• The matrix indices must be positive integer

Given:
Working with Matrices
MATLAB provides five functions that generate basic matrices:
• Zeros: all zeros. A = zeros(1,3)
• Ones: all ones. A = ones(2,4)
• eye(3,3)?
• rand: uniformly distributed random elements.
A = rand(3,5)
• randn: normally distributed random elements.
A = randn(2,5)
Set the state of the random number generator
rand(‘state’,2); randn(‘state’,2);
Single (closing) quotes act as string delimiters, so 'state' is a string. Many
MATLAB functions take string arguments.
Data Import and Export
Import Wizard
• Import wizard provides flexible data possibilities
• File -> Import data
• Provides working directory and various file format
• importdata – Load data from file
• uiimport – import data interactively
File Formats for Import and Export
FILE CONTENT EXTENSION IMPORT EXPORT
FUNCTION FUNCTION
MATLAB formatted MAT Load save
data
Text TXT csvread csvwrite
Spreadsheet XLS xlsread xlswrite
Extensible Markup XML xmlread xmlwrite
Language
Data acquisition DAQ Dadread none
Toolbox
Image BMP,JPEG,TIFF,GI imread imwrite
F
Audio MP4,M4A,WAV audioread Audiowrite
Video MPEG,M4V,MOV Videoreader videowriter
M-files :
Script and function files
When problems become complicated and require re–evaluation,
entering command at MATLAB prompt is not practical

Solution : use M-files

Script Function
Collections of commands User defined commands

Executed in sequence when called Normally has input & output

Saved with extension “.m” Saved with extension “.m”


M-files : script and function files (script)

At Matlab prompt type in edit to invoke M-file editor

Save this file as


test1.m
M-files : script and function files (script)

To run the M-file, type in the name of the file at the


prompt e.g. >>> test1

It will be executed provided that the saved file is in the


known path

Type in matlabpath to check the list of directories


listed in the path
Use path editor to add the path: File  Set path …
Functions

• Function is a ‘black box’ that communicates with workspace through


input and output variables.

INPUT OUTPUT
FUNCTION
– Commands
– Functions
– Intermediate variables
Every function must begin with a header:

function output=function_name(inputs)

Output variable
Must match the file input variable
name
• Functions are M-files that can accept input arguments and return output
arguments. The names of the M-file and of the function should be the
same.
• Example

Task:

function [A] = area(a,b,c)


File area.m: s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c));

Usage example: To evaluate the area of a triangle with side of length 10, 15, 20:

>> Area = area(10,15,20)


Area =72.6184
Arithmetic Operations
• Addition + >> 1+2
• Subtraction - >> 3-4
• Multiplication * >> 5*6
• Division / >> 7/8
• Back Slash \ >> 9\10 or 10/9
• Exponentiation ^ >> 2^3
• Priority rule :
PEMDAS (Parentheses, Exponentiation, Multiplication,
Division, Addition, Subtraction)
>> ((2+5)^2+2*2-10/5)  = ?
Priority rules
• Precedence is the order operations are
preformed, remember PEMDAS
• >> ((2+5)^2+2*2-10/5) innermost
parentheses is done first
– 7^2 exponentiation is next
– 2*2 or 10/5 multiplication or division next
– (49 + 4 – 2) addition or subtraction next
• Operations are done from left to right
 final result gives 51
FLOW CONTROL
CONTROL FLOW SWITCH CASE
WHILE LOOP
Solutions to Systems of Linear Equations
• Example: a system of 3 linear equations with 3 unknowns (x1, x2, x3):
3x1 + 2x2 - x3 = 10
-x1 + 3x2 + 2x3 = 5
x1 – x2 – x3 = -1
Let :
 3 2 1  x1   10 
A   1 3 2  x  x2  b  5 
 
 1  1  1  x3    1

Then, the system can be described as:

Ax = b
Solutions to Systems of Linear Equations
(con’t…)
• Solution by Matrix Inverse: • Solution by Matrix Division:
Ax = b The solution to the equation
A-1Ax = A-1b Ax = b
x = A-1b can be computed using left division.
• MATLAB:  MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1]; >> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1]; >> b = [ 10; 5; -1];
>> x = inv(A)*b >> x = A\b
x= x=
-2.0000 -2.0000
5.0000 5.0000
-6.0000 -6.0000
Answer: Answer:
x1 = -2, x2 = 5, x3 = -6 x1 = -2, x2 = 5, x3 = -6

NOTE:
left division: A\b  b  A right division: x/y  x  y
Solution of Differential Equations with
MATLAB

•MATLAB has some powerful features for


solving differential equations of all types. We
will explore some of these features for the
CCLODE forms. The approach here will be
that of the Symbolic Math Toolbox. The result
will be the form of the function and it may be
readily plotted with MATLAB.

53
Symbolic Differential Equation Terms

y •y

dy •Dy
dt
2
d y
•D2y
2
dt
n
d y
n
•Dny
dt
54
Representative CCLODE Form
2
d y dy
b2 2  b1  b0 y  A sin at
dt dt
y (0) C1 and y '(0) C2
•>> y = dsolve(‘b2*D2y+b1*D1y+b0*y=A*sin(a*t)’,
• ‘y(0)=C1’, ‘Dy(0)=C2’)

•>> ezplot(y, [t1 t2])

55
Example 1. Solve DE below with MATLAB.
dy y (0) 10
 2 y 12
dt
•>> y = dsolve('Dy + 2*y = 12', 'y(0)=10')
•y =
•6+4*exp(-2*t)

•>> ezplot(y, [0 3])


•>>
56
57
Example 2. Solve DE below with MATLAB.
dy y (0) 10
 2 y 12sin 4t
dt
•>> y = dsolve('Dy + 2*y = 12*sin(4*t)',
'y(0)=10')
•y =
• -12/5*cos(4*t)+6/5*sin(4*t)+62/5*exp(-2*t)

•>> ezplot(y, [0 8])


•>> axis([0 8 -3 10])

58
59
Example 3. Solve DE below with MATLAB.
2
d y dy
2
 3  2 y 24
dt dt
y (0) 10 y '(0) 0
•>> y = dsolve('D2y + 3*Dy + 2*y = 24',
'y(0)=10', 'Dy(0)=0')
•y =
•12+2*exp(-2*t)-4*exp(-t)

•>> ezplot(y, [0 6])

60
61
Example 4. Solve
2
DE below with MATLAB.
d y dy
2
 2  5 y 20
dt dt
y (0) 0 y '(0) 10

•>> y = dsolve('D2y + 2*Dy + 5*y = 20',


• 'y(0) = 0', 'Dy(0) = 10')
•y =
•4+3*exp(-t)*sin(2*t)-4*exp(-t)*cos(2*t)

•>>ezplot(y, [0 5]}
62
63
STRUCTURES IN MATLAB
STANDARD MATHEMATICAL FUNCTION
PLOT THE SINE, COSINE FUNCTION
Title Adding
Indefinite Integrals
DEFINITE INTEGRAL
TRANSFORMS
Symbolic Laplace Transform

•Establish t and s as symbolic variables.


•>> syms t s
•The time function f is then formed and the
Laplace transform command is
•>> F = laplace(f)
•Some useful simplifications are
•>> pretty(F)
•>> simplify(F)
77
Symbolic Inverse Laplace Transform

•Establish t and s as symbolic variables.


•>> syms t s
•The Laplace function F is then formed and the
inverse Laplace transform command is
•>> f = ilaplace(F)

•The simplification operations may also be


useful for inverse transforms.
78
Example 5. Determine the Laplace
transform of f(t)=5t with MATLAB.
•>>syms t s
•>> f = 5*t
•f =
•5*t

•>> F = laplace(f)
•F =
• 5/s^2
81
Example 6. Determine the Laplace transform of
the function below using MATLAB.

 2t  2t
v(t ) 3e sin 5t  4e cos 5t
•>> syms t s
•>> v = 3*exp(-2*t)*sin(5*t)
• + 4*exp(-2*t)*cos(5*t)
•v =
•3*exp(-2*t)*sin(5*t)+4*exp(-2*t)*cos(5*t)

82
Example 6. Continuation.

•>> V = laplace(v)
•V =
•15/((s+2)^2+25)+4*(s+2)/((s+2)^2+25)

•>> V=simplify(V)
•V =
• (23+4*s)/(s^2+4*s+29)

83
Example 7. Determine the inverse transform
of the function below using MATLAB.
100( s  3)
F (s)  2
( s  1)( s  2)( s  2 s  5)
•>> syms t s

•>> F=100*(s+3)/((s+1)*(s+2)*(s^2+2*s+5))
•F =
•(100*s+300)/(s+1)/(s+2)/(s^2+2*s+5)

84
Example 11-7. Continuation.

•>> f = ilaplace(F)

•f =
• 50*exp(-t)-20*exp(-2*t)-30*exp(-t)*cos(2*t)-10*exp(-
t)*sin(2*t)

•>> pretty(f)
• 50 exp(-t) - 20 exp(-2 t) - 30 exp(-t) cos(2 t) - 10 exp(-t) sin(2
t)

85
Example 11-8. Determine the inverse transform
of the function below using MATLAB.

10 48
Y (s)   2
s  2 ( s  2)( s  16)
•>> syms t s
•>> Y = 10/(s+2) + 48/((s+2)*(s^2+16))
•Y =
•10/(s+2)+48/(s+2)/(s^2+16)

86
Example 8. Continuation.
•>> y = ilaplace(Y)
•y =
•62/5*exp(-2*t)-12/5*cos(16^(1/2)*t)
+3/10*16^(1/2)*sin(16^(1/2)*t)

•>> y=simplify(y)
•y =
•62/5*exp(-2*t)-12/5*cos(4*t)+6/5*sin(4*t)

87
Two Dimensional Plots

Topics Covered:
1. Plotting basic 2-D plots.

The plot command.

The fplot command.


Plotting multiple graphs in the same
plot.
Formatting plots.
MAKING X-Y PLOTS

MATLAB has many functions and commands that can be used to create various
types of plots.

create two dimensional x – y plots.


EXAMPLE OF A 2-D PLOT Legend
Plot title
Light Intensity as a Function of Distance
1200
Theory
y axis Experiment

label 1000

Text
Tick-mark
800
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
TWO-DIMENSIONAL plot() COMMAND
The basic 2-D plot command is:

plot(x,y)

where x is a vector (one dimensional array), and y is a vector.


Both vectors must have the same number of elements.

 The plot command creates a single curve with the x values on


the abscissa (horizontal axis) and the y values on the ordinate
(vertical axis).

 The curve is made from segments of lines that connect the


points that are defined by the x and y coordinates of the
elements in the two vectors.
PLOT OF GIVEN DATA
Given data:

x 1 2 3 5 7 7.5 8 10

y 2 6.5 7 7 5.5 4 6 8

A plot can be created by the commands shown below. This can be done in the
Command Window, or by writing and then running a script file.

>> x=[1 2 3 5 7 7.5 8 10];


>> y=[2 6.5 7 7 5.5 4 6 8];
>> plot(x,y)

Once the plot command is executed, the Figure Window opens with the following
plot.
PLOT OF GIVEN DATA
LINE SPECIFIERS IN THE plot() COMMAND

Line specifiers can be added in the plot command to:


 Specify the style of the line.
 Specify the color of the line.
 Specify the type of the markers (if markers are desired).

plot(x,y,’line specifiers’)
LINE SPECIFIERS IN THE plot() COMMAND

plot(x,y,‘line specifiers’)
LINE SPECIFIERS IN THE plot() COMMAND
 The specifiers are typed inside the plot() command as strings.

 Within the string the specifiers can be typed in any order.

 The specifiers are optional. This means that none, one, two, or all the three
can be included in a command.

EXAMPLES:

plot(x,y) A solid blue line connects the points with no markers.


plot(x,y,’r’) A solid red line connects the points with no markers.
plot(x,y,’--y’) A yellow dashed line connects the points.
plot(x,y,’*’) The points are marked with * (no line between the
points.)
plot(x,y,’g:d’) A green dotted line connects the points which are
marked with diamond markers.
PLOT OF GIVEN DATA USING LINE SPECIFIERS IN
THE plot() COMMAND

Year 1988 1989 1990 1991 1992 1993 1994

Sales (M) 127 130 136 145 158 178 211

>> year = [1988:1:1994];


>> sales = [127, 130, 136, 145, 158, 178, 211];
>> plot(year,sales,'--r*')

Line Specifiers:
dashed red line and
asterisk markers.
PLOT OF GIVEN DATA USING LINE SPECIFIERS IN
THE plot() COMMAND

Dashed red line and


asterisk markers.
CREATING A PLOT OF A FUNCTION

 0 .5 x
Consider: y 3.5 cos(6 x) for  2  x 4
A script file for plotting the function is:

% A script file that creates a plot of


% the function: 3.5^(-0.5x)*cos(6x)
x = [-2:0.01:4];
Creating a vector with spacing of 0.01.
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y) Calculating a value of y
for each x.

Once the plot command is executed, the Figure Window opens with the following
plot.
A PLOT OF A FUNCTION
 0 .5 x
y 3.5 cos(6 x) for  2  x 4
CREATING A PLOT OF A FUNCTION

If the vector x is created with large spacing, the graph is not accurate.
Below is the previous plot with spacing of 0.3.

x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
THE fplot COMMAND

The fplot command can be used to plot a function


with the form: y = f(x)

fplot(‘function’,limits)

 The function is typed in as a string.

 The limits is a vector with the domain of x, and optionally with limits of the y
axis:

[xmin,xmax] or [xmin,xmax,ymin,ymax]
 Line specifiers can be added.
PLOT OF A FUNCTION WITH THE fplot() COMMAND
A plot of: y  x 2  4 sin( 2 x)  1 for  3  x 3

>> fplot('x^2 + 4 * sin(2*x) - 1', [-3 3])


PLOTTING MULTIPLE GRAPHS IN THE SAME PLOT

Plotting two (or more) graphs in one plot:

1. Using the plot command.

2. Using the hold on, hold off commands.


USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

plot(x,y,u,v,t,h)

Plots three graphs in the same plot:

y versus x, v versus u, and h versus t.


 By default, MATLAB makes the curves in different colors.
 Additional curves can be added.
 The curves can have a specific style by adding specifiers after each pair, for
example:

plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

Plot of the function, y 3 x 3  26 x  10 and its first and second


derivatives, for  2 x 
, 4 all in the same plot.

x = [-2:0.01:4]; vector x with the domain of the function.


y = 3*x.^3-26*x+6;
 2  xy
Vector 4with the function value at each x.
yd = 9*x.^2-26;
Vector yd with values of the first derivative.
ydd = 18*x;
Vector ydd with values of the second derivative.
 2  x 4
plot(x,y,'-b',x,yd,'--r',x,ydd,':k')

Create three graphs, y vs. x (solid blue line), yd vs.


x (dashed red line), and ydd vs. x (dotted black
line) in the same figure.
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT

120

100

80

60

40

20

-20

-40
-2 -1 0 1 2 3 4
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT

hold on Holds the current plot and all axis properties so that subsequent
plot commands add to the existing plot.

hold off Returns to the default mode whereby plot commands erase the
previous plots and reset all axis properties before drawing new
plots.

This method is useful when all the information (vectors) used for the plotting
is not available a the same time.
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function, y 3 x 3  26 x  10 and its first and second
derivatives, for  2  x 4 all in the same plot.

x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
First graph is created.
hold on
plot(x,yd,'--r')
plot(x,ydd,':k') Two more graphs are created.
hold off
EXAMPLE OF A FORMATTED 2-D PLOT
Plot title
Light Intensity as a Function of Distance
1200 Legend
Theory
y axis Experiment

label 1000

Text
800
Tick-mark
INTENSITY (lux)

Comparison between theory and experiment.

600

400
Data symbol

200

0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
FORMATTING PLOTS

A plot can be formatted to have a required appearance.

With formatting you can:

 Add title to the plot.


 Add labels to axes.
 Change range of the axes.
 Add legend.
 Add text blocks.
 Add grid.
FORMATTING PLOTS

There are two methods to format a plot:

1. Formatting commands.
In this method commands, that make changes or additions to the plot, are
entered after the plot() command. This can be done in the Command
Window, or as part of a program in a script file.

2. Formatting the plot interactively in the Figure Window.


In this method the plot is formatted by clicking on the plot and using the
menu to make changes or add details.
FORMATTING COMMANDS

title(‘string’)
Adds the string as a title at the top of the plot.

xlabel(‘string’)
Adds the string as a label to the x-axis.

ylabel(‘string’)
Adds the string as a label to the y-axis.

axis([xmin xmax ymin ymax])


Sets the minimum and maximum limits of the x- and y-axes.
FORMATTING COMMANDS

legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when several
curves are in one plot). The location of the legend is specified by the mouse.

text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to the plot axes.

gtext(‘string’)
Places the string (text) on the plot. When the command executes the figure
window pops and the text location is clicked with the mouse.
EXAMPLE OF A FORMATTED PLOT
Below is a script file of the formatted light intensity plot (2nd slide).
(Some of the formatting options were not covered in the lectures, but are
described in the book)

x=[10:0.1:22]; Creating vector x for plotting the theoretical curve.


y=95000./x.^2; Creating vector y for plotting the theoretical curve.
xd=[10:2:22];
Creating a vector with coordinates of data points.
yd=[950 640 460 340 250 180 140];
Creating a vector with light
plot(x,y,'-','LineWidth',1.0) intensity from data.
hold on
plot(xd,yd,'ro--','linewidth',1.0,'markersize',10)
hold off
EXAMPLE OF A FORMATTED PLOT

Formatting of the light intensity plot (cont.)

xlabel('DISTANCE (cm)')
Labels for the axes.
ylabel('INTENSITY (lux)')
Title for the plot.
title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)
axis([8 24 0 1200])
text(14,700,'Comparison between theory and
Setting limits of the axes.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating text.

Creating a legend.

The plot that is obtained is shown again in the next slide.


FORMATTING A PLOT IN THE FIGURE WINDOW
Once a figure window is open, the figure can be formatted interactively.
Use the insert menu to

Use Figure, Axes, Click here to start the plot


and Current edit mode.
Object-Properties
in the Edit menu
Illustration
0.7

0.6

0.5

• plot(.) 0.4

0.3

0.2
Example: 0.1
>>x=linspace(0,4*pi,100); 0

>>y=sin(x); -0.1

>>plot(y) -0.2

>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100

0.7

• stem(.) 0.6

0.5

0.4

0.3

0.2
Example: 0.1

>>stem(y) 0

>>stem(x,y) -0.1

-0.2

-0.3
0 10 20 30 40 50 60 70 80 90 100
• title(.)
This is the sinus function
1
>>title(‘This is the sinus function’)
0.8

0.6

• xlabel(.)
0.4

0.2

sin(x)
>>xlabel(‘x (secs)’)
-0.2

-0.4

-0.6
• ylabel(.) -0.8

-1
0 10 20 30 40 50 60 70 80 90 100
>>ylabel(‘sin(x)’) x (secs)
A simple example:

a=1
while length(a) < 10
which prints out Pascal’s triangle:
a = [0 a] + [a 0]
end
1
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1

(with “a=” before each line).


Using Matlab to create models

• Why model?
- Represent
- Analyze

• What kind of systems are we interested?


- Single-Input-Single-Output (SISO)
- Linear Time Invariant (LTI)
- Continuous

X(s) G(s) Y(s)

124
Model representations

Three Basic types of model representations for continuous LTI systems:

• Transfer Function representation (TF)

• Zero-Pole-Gain representation (ZPK)

• State Space representation (SS)

! More help is available for each model representation by typing:


help ltimodels

125
Transfer Function representation

Given: G(s ) Y (s )  25
U (s ) s 2  4s  25

Matlab function: tf

Method (a) Method (b)

num = [0 0 25]; s = tf('s');


den = [1 4 25]; G = 25/(s^2 +4*s +25)
G = tf(num,den)

126
Zero-Pole-Gain representation

Given: H (s ) Y (s )  3(s  1)
U (s ) (s  2  i )(s  2  i )

Matlab function: zpk

zeros = [1];
poles = [2-i 2+i];
gain = 3;
H = zpk(zeros,poles,gain)

127
State Space representation

  1 0  1
Given:  x  Ax  Bu, A   B  
   2 1   0
 y Cx  Du
C  3  2 D  0

Matlab function: ss

A = [1 0 ; -2 1];
B = [1 0]’;
C = [3 -2];
D = [0];
sys = ss(A,B,C,D)

128
System analysis

• Once a model has been introduced in Matlab, we can use a series of


functions to analyze the system.

• Key analyses at our disposal:


1) Stability analysis
e.g. pole placement
2) Time domain analysis
e.g. response to different inputs
3) Frequency domain analysis
e.g. bode plot

129
Stability analysis
Is the system stable?

Recall: All poles of the system must be on the right hand side of the S plain
for continuous LTI systems to be stable.

Manually: Poles are the roots for the denominator of transfer


functions or eigen values of matrix A for state space
representations

In Matlab:

pole(sys)

130
Time domain analysis
Once a model has been inserted in Matlab, the step response can be
obtained directly from: step(sys)

Unit Step Response of G(s)


1.4

1.2 Steady State


overshoot
1
Amplitude

0.8

0.6

0.4 Settling Time


0.2 Peak Time

0 0.5 1 1.5 2 2.5 3


Time (sec)
131
Rise Time
Time domain analysis
Matlab also caries other useful functions for time domain analysis:

• Impulse response
impulse(sys)
• Response to an arbitrary input
e.g.
t = [0:0.01:10];
u = cos(t);
lsim(sys,u,t)

! It is also possible to assign a variable to those functions to obtain a


vector with the output. For example: y = impulse(sys);
132
Frequency domain analysis
Bode plots can be created directly by using: bode(sys)

133
Frequency domain analysis
For a pole and zero plot: pzmap(sys)

Pole-Zero Map
4

1
Imaginary Axis

-1

-2

-3

-4
-2 -1.8 -1.6 -1.4 -1.2 -1 -0.8 -0.6 -0.4 -0.2 0
Real Axis

134
Extra: partial fraction expansion
Given: 2s 2  3s  2
G ( s)  2
s  3s  2
num=[2 3 2];
den=[1 3 2];
[r,p,k] = residue(num,den)

r= Answer:
-4
1 r (1) r ( n)
p= G ( s) k ( s)   
-2
-1  0
s  p(1)
4 1
s  p ( n)
k= 2s  
2 s  ( 2) s  ( 1)

135

You might also like