1 Lab Experiment 1: Using MATLAB for Control Systems
Lab Experiment 1
Using MATLAB for Control Systems
Objectives:
This lab introduces MATLAB in the first part. The lab also provides tutorial of polynomials,
script writing and programming aspect of MATLAB fromcontrol systems viewpoint.
List of Equipment/Software
Following equipment/software is required:
• MATLAB
Deliverables
A complete lab report including the following:
• Summarized learning outcomes.
• MATLAB scripts and their results should be reported properly.
Part I: Introduction to MATLAB
The objective of this exercise will be to introduce you to the concept of mathematical
programming using the software called MATLAB. We shall study how to define variables,
matrices etc, see how we can plot results and write simple MATLAB codes.
MATLAB TUTORIAL
Reference: Engineering Problem Solving Using MATLAB, by Professor Gary Ford, University of California, Davis.
EE 332 Control Systems 1
2 Lab Experiment 1: Using MATLAB for Control
Topics
Introduction
MATLAB Environment
Getting Help
Variables
Vectors, Matrices, and Linear Algebra
Plotting
Introduction
What is MATLAB?
• MATLAB is a computer program that combines computation and
visualization power that makes it particularly useful tool for
engineers.
• MATLAB is an executive program, and a script can be made with a
list of MATLAB commands like other programming language.
MATLAB Stands for MATrix LABoratory.
• The system was designed to make matrix computation particularly easy.
The MATLAB environment allows the user to:
• manage variables
• import and export data
• perform calculations
• generate plots
• develop and manage files for use with MATLAB.
MATLAB
Environment
To start MATLAB:
START PROGRAMS
MATLAB 6.5 MATLAB
6.5
Or shortcut creation/activation
on the desktop
EE 332 Control Systems 2
3 Lab Experiment 1: Using MATLAB for Control Systems
Display Windows
Display Windows (con’t…)
Graphic (Figure) Window
Displays plots and graphs
Created in response to graphics
commands.
M-file editor/debugger window
Create and edit scripts of commands called
M-files.
Getting Help
type one of following commands in the command
window:
help – lists all the help topic
help topic – provides help for the specified topic
help command – provides help for the specified command
help help – provides information on use of the help command
helpwin – opens a separate help window for navigation
lookfor keyword – Search all M-files for keyword
EE 332 Control Systems 3
4 Lab Experiment 1: Using MATLAB for Control Systems
Variables
Variable names:
Must start with a letter
May contain only letters, digits, and the underscore “_”
Matlab is case sensitive, i.e. one & OnE are different variables.
Matlab only recognizes the first 31 characters in a variable name.
Assignment statement:
Variable = number;
Variable = expression;
Example: NOTE: when a semi-colon
>> tutorial = 1234; ”;” is placed at the end of
>> tutorial = 1234
tutorial = each command, the result
1234 is not displayed.
Variables (con’t…)
Special variables:
ans : default variable name for the result
pi: π = 3.1415926…………
eps: ∈ = 2.2204e-016, smallest amount by which 2 numbers can differ.
Inf or inf : ∞, infinity
NaN or nan: not-a-number
Commands involving variables:
who: lists the names of defined variables
whos: lists the names and sizes of defined variables
clear: clears all varialbes, reset the default values of special
variables.
clear name: clears the variable name
clc: clears the command window
clf: clears the current figure and the graph window.
Vectors, Matrices and Linear Algebra
Vectors
Matrices
Array Operations
Solutions to Systems of Linear
Equations.
EE 332 Control Systems 4
5 Lab Experiment 1: Using MATLAB for Control Systems
Vectors
A row vector in MATLAB can be created by an explicit list, starting with a left bracket,
entering the values separated by spaces (or commas) and closing the vector with a right
bracket.
A column vector can be created the same way, and the rows are separated by semicolons.
Example:
>> x = [ 0 0.25*pi 0.5*pi 0.75*pi pi ]
x=
0 0.7854 1.5708 2.3562 3.1416 x is a row vector.
>> y = [ 0; 0.25*pi; 0.5*pi; 0.75*pi; pi ]
y=
0
0.7854 y is a column vector.
1.5708
2.3562
3.1416
Vectors (con’t…)
Vector Addressing – A vector element is addressed in MATLAB with an integer
index enclosed in parentheses.
Example:
>> x(3)
ans =
1.5708 3rd element of vector x
The colon notation may be used to address a block of elements.
(start : increment : end)
start is the starting index, increment is the amount to add to each successive index, and end
is the ending index. A shortened format (start : end) may be used if increment is 1.
Example:
>> x(1:3)
ans =
0 0.7854 1.5708 1st to 3rd elements of vector x
NOTE: MATLAB index starts at 1.
Vectors (con’t…)
Some useful commands:
x = start:end create row vector x starting with start, counting by
one, ending at end
x = start:increment:end create row vector x starting with start, counting by
increment, ending at or before end
linspace(start,end,number) create row vector x starting with start, ending at
end, having number elements
length(x) returns the length of vector x
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.
EE 332 Control Systems 5
6 Lab Experiment 1: Using MATLAB for Control Systems
Matrices
A Matrix array is two-dimensional, having both multiple rows and multiple columns,
similar to vector arrays:
it begins with [, and end with ]
spaces or commas are used to separate elements in a row
semicolon or enter is used to separate rows.
•Example:
A is an m x n matrix.
>> f = [ 1 2 3; 4 5 6]
f=
1 2 3
4 5 6
>> h = [ 2 4 6
1 3 5]
h=
2 4 6
1 3 5
the main diagonal
Matrices (con’t…)
Magic Function
For example you can generate a matrix by entering
>> m=magic(4)
It generates a matrix whose elements are such that the sum of all elements in
its rows, columns and diagonal elements are same
Sum Function
You can verify the above magic square by entering
>> sum(m)
For rows take the transpose and then take the sum
>> sum(m’)
Diag
You can get the diagonal elements of a matrix by entering
>> d=diag(m)
>> sum(d)
Matrices (con’t…)
Matrix Addressing:
-- matrixname(row, column)
-- colon may be used in place of a row or column reference to select
the entire row or column.
Example:
recall:
>> f(2,3) f=
ans = 1 2 3
6 4 5 6
>> h(:,1) h=
ans = 2 4 6
2
1 3 5
1
EE 332 Control Systems 6
7 Lab Experiment 1: Using MATLAB for Control Systems
Matrices (con’t…)
Some useful commands:
zeros(n) returns a n x n matrix of zeros
zeros(m,n) returns a m x n matrix of zeros
ones(n) returns a n x n matrix of ones
ones(m,n) returns a m x n matrix of ones
rand(n) returns a n x n matrix of random number
rand(m,n) returns a m x n matrix of random number
size (A) for a m x n matrix A, returns the row vector [m,n]
containing the number of rows and columns in
matrix.
length(A) returns the larger of the number of rows or
columns in A.
Matrices (con’t…)
more commands
Transpose B = A’
Identity Matrix eye(n) returns an n x n identity matrix
eye(m,n) returns an m x n matrix with ones on the main
diagonal and zeros elsewhere.
Addition and subtraction C=A+B
C=A–B
Scalar Multiplication B = αA, where α is a scalar.
Matrix Multiplication C = A*B
Matrix Inverse B = inv(A), A must be a square matrix in this case.
rank (A) returns the rank of the matrix A.
Matrix Powers B = A.^2 squares each element in the matrix
C = A * A computes A*A, and A must be a square matrix.
Determinant det (A), and A must be a square matrix.
A, B, C are matrices, and m, n, α are scalars.
Array Operations
Scalar-Array Mathematics
For addition, subtraction, multiplication, and division of an array by a
scalar simply apply the operations to all elements of the array.
Example:
>> f = [ 1 2; 3 4]
f=
1 2
3 4
>> g = 2*f – 1 Each element in the array f is
g=
1 3 multiplied by 2, then subtracted
5 7 by 1.
EE 332 Control Systems 7
8 Lab Experiment 1: Using MATLAB for Control Systems
Array Operations (con’t…)
Element-by-Element Array-Array Mathematics.
Operation Algebraic Form M ATLAB
Addition a+b a+b
Subtraction a–b a–b
Multiplication axb a .* b
Division a÷b a ./ b
Exponentiation ab a .^ b
Example:
>> x = [ 1 2 3 ];
>> y = [ 4 5 6 ];
Each element in x is multiplied by
>> z = x .* y the corresponding element in y.
z=
4 10 18
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
EE 332 Control Systems 8
9 Lab Experiment 1: Using MATLAB for Control Systems
Plotting
For more information on 2-D plotting, type help graph2d
Plotting a point: the function plot () creates a
>> plot ( variablename, ‘symbol’) graphics window, called a Figure
window, and named by default
“Figure No. 1”
Example : Complex number
>> z = 1 + 0.5j;
>> plot (z, ‘.’)
commands for axes:
command description
axis ([xmin xmax ymin ymax]) Define minimum and maximum values of the axes
axis square Produce a square plot
axis equal equal scaling factors for both axes
axis normal turn off axis square, equal
axis (auto) return the axis to defaults
Plotting (con’t…)
Plotting Curves:
plot (x,y) – generates a linear plot of the values of x (horizontal axis) and y
(vertical axis).
semilogx (x,y) – generate a plot of the values of x and y using a logarithmic
scale for x and a linear scale for y
semilogy (x,y) – generate a plot of the values of x and y using a linear scale
for x and a logarithmic scale for y.
loglog(x,y) – generate a plot of the values of x and y using logarithmic scales
for both x and y
Plotting (con’t…)
Multiple Curves:
plot (x, y, w, z) – multiple curves can be plotted on the same graph by using
multiple arguments in a plot command. The variables x, y, w, and z are
vectors. Two curves will be plotted: y vs. x, and z vs. w.
legend (‘string1’, ‘string2’,…) – used to distinguish between plots on the
same graph
Multiple Figures:
figure (n) – used in creation of multiple plot windows. place this command
before the plot() command, and the corresponding figure will be labeled as
“Figure n”
close – closes the figure n window.
close all – closes all the figure windows.
Subplots:
subplot (m, n, p) – m by n grid of windows, with p specifying the
current plot as the pth window
EE 332 Control Systems 9
10 Lab Experiment 1: Using MATLAB for Control Systems
Plotting (con’t…)
Example: (polynomial function)
plot the polynomial using linear/linear scale, log/linear scale, linear/log scale, & log/log
scale:
y = 2x2 + 7x + 9
% Generate the polynomial:
x = linspace (0, 10, 100);
y = 2*x.^2 + 7*x + 9;
% plotting the polynomial:
figure (1);
subplot (2,2,1), plot (x,y);
title ('Polynomial, linear/linear scale');
ylabel ('y'), grid;
subplot (2,2,2), semilogx (x,y);
title ('Polynomial, log/linear scale');
ylabel ('y'), grid;
subplot (2,2,3), semilogy (x,y);
title ('Polynomial, linear/log scale');
xlabel('x'), ylabel ('y'), grid;
subplot (2,2,4), loglog (x,y);
title ('Polynomial, log/log scale');
xlabel('x'), ylabel ('y'), grid;
Plotting (con’t…)
Plotting (con’t…)
Adding new curves to the existing graph:
Use the hold command to add lines/points to an existing plot.
hold on – retain existing axes, add new curves to current axes. Axes are
rescaled when necessary.
hold off – release the current figure window for new plots
Grids and Labels:
Command Description
grid on Adds dashed grids lines at the tick marks
grid off removes grid lines (default)
grid toggles grid status (off to on, or on to off)
title (‘text’) labels top of plot with text in quotes
xlabel (‘text’) labels horizontal (x) axis with text is quotes
ylabel (‘text’) labels vertical (y) axis with text is quotes
text (x,y,’text’) Adds text in quotes to location (x,y) on the current axes, where (x,y) is in
units from the current plot.
EE 332 Control Systems 10
11 Lab Experiment 1: Using MATLAB for Control Systems
Additional commands for plotting
color of the point or curve Marker of the data points Plot line styles
Symbol Color Symbol Marker Symbol Line Style
y yellow . • – solid line
m magenta o ° : dotted line
c cyan x × –. dash-dot line
r red + + –– dashed line
g green * ∗
b blue s □
w white d ◊
k black v ∇
^ ∆
h hexagram
Exercise 1:
Use Matlab command to obtain the following
a) Extract the fourth row of the matrix generated by magic(6)
b) Show the results of ‘x’ multiply by ‘y’ and ‘y’ divides by ‘x’.
Given x = [0:0.1:1.1] and y = [10:21]
c) Generate random matrix ‘r’ of size 4 by 5 with number varying between -8 and 9
Exercise 2:
Use MATLAB commands to get exactly as the figure shown below
x=pi/2:pi/10:2*pi;
y=sin(x);
z=cos(x);
EE 332 Control Systems 11