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

CISE-302-Linear-Control-Systems-Lab-Manual 1

This document provides an introduction and overview of MATLAB for control systems. It describes the objectives of the lab which are to introduce MATLAB and provide tutorials on polynomials, script writing and programming aspects from a control systems perspective. The document lists the required equipment as MATLAB and describes the deliverables as a lab report summarizing learning outcomes and including MATLAB scripts and results. It then provides an introduction to MATLAB describing what it is and its capabilities, and gives an overview of the MATLAB environment and how to get help. Human: Thank you for the summary. You captured the key details effectively in 3 sentences.

Uploaded by

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

CISE-302-Linear-Control-Systems-Lab-Manual 1

This document provides an introduction and overview of MATLAB for control systems. It describes the objectives of the lab which are to introduce MATLAB and provide tutorials on polynomials, script writing and programming aspects from a control systems perspective. The document lists the required equipment as MATLAB and describes the deliverables as a lab report summarizing learning outcomes and including MATLAB scripts and results. It then provides an introduction to MATLAB describing what it is and its capabilities, and gives an overview of the MATLAB environment and how to get help. Human: Thank you for the summary. You captured the key details effectively in 3 sentences.

Uploaded by

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

4 Lab Experiment 1: Using MATLAB for Control Systems

CISE 302
Linear Control Systems
Lab Experiment 1: Using MATLAB for Control Systems
Objectives: This lab provides an introduction to MATLAB in the first part. The lab also
provides tutorial of polynomials, script writing and programming aspect of MATLAB from
control systems view point.

List of Equipment/Software
Following equipment/software is required:

 MATLAB

Category Soft-Experiment

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


Objective: 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.

___________________________________

CISE 302 Lab Manual Page 4


5 Lab Experiment 1: Using MATLAB for Control Systems

___________________________________

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
___________________________________

___________________________________

___________________________________

___________________________________

CISE 302 Lab Manual Page 5


6 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
___________________________________

___________________________________

___________________________________

CISE 302 Lab Manual Page 6


7 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.
___________________________________

___________________________________

___________________________________

CISE 302 Lab Manual Page 7


8 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
returns the length of vector x
___________________________________
length(x)
y = x’ transpose of vector x
dot (x, y) returns the scalar dot product of the vector x and y.
___________________________________

___________________________________

___________________________________

CISE 302 Lab Manual Page 8


9 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 ___________________________________

___________________________________

CISE 302 Lab Manual Page 9


10 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

Scalar Multiplication
C=A–B
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
g=
Each element in the array f is
multiplied by 2, then subtracted
1
5
3
7 by 1. ___________________________________

___________________________________

___________________________________

CISE 302 Lab Manual Page 10


11 Lab Experiment 1: Using MATLAB for Control Systems

___________________________________

Array Operations (con’t…) ___________________________________


 Element-by-Element Array-Array Mathematics.
Operation Algebraic Form MATLAB
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
x = A-1b
Ax = b
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];
>> x = inv(A)*b
>> b = [ 10; 5; -1];
>> 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

___________________________________

CISE 302 Lab Manual Page 11


12 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
axis (auto)
turn off axis square, equal
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

___________________________________

CISE 302 Lab Manual Page 12


13 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
grid on
Description
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.

___________________________________

___________________________________

CISE 302 Lab Manual Page 13


14 Lab Experiment 1: Using MATLAB for Control Systems

___________________________________

Additional commands for plotting


___________________________________

color of the point or curve


Symbol Color
Marker of the data points
Symbol Marker
Plot line styles
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);

CISE 302 Lab Manual Page 14


15 Lab Experiment 1: Using MATLAB for Control Systems

Part II: Polynomials in MATLAB

Objective: The objective of this session is to learn how to represent polynomials in


MATLAB, find roots of polynomials, create polynomials when roots are known and obtain
partial fractions.

Polynomial Overview:
MATLAB provides functions for standard polynomial operations, such as polynomial roots,
evaluation, and differentiation. In addition, there are functions for more advanced
applications, such as curve fitting and partial fraction expansion.

Polynomial Function Summary


Function Description
Conv Multiply polynomials
Deconv Divide polynomials
Poly Polynomial with specified roots
Polyder Polynomial derivative
Polyfit Polynomial curve fitting
Polyval Polynomial evaluation
Polyvalm Matrix polynomial evaluation
Residue Partial-fraction expansion (residues)
Roots Find polynomial roots

Symbolic Math Toolbox contains additional specialized support for polynomial operations.

Representing Polynomials
MATLAB represents polynomials as row vectors containing coefficients ordered by
descending powers. For example, consider the equation

( )

This is the celebrated example Wallis used when he first represented Newton's method to the
French Academy. To enter this polynomial into MATLAB, use

>>p = [1 0 -2 -5];

Polynomial Roots
The roots function calculates the roots of a polynomial:

>>r = roots(p)

r=
2.0946
-1.0473 + 1.1359i
-1.0473 - 1.1359i

By convention, MATLAB stores roots in column vectors. The function poly returns to the
polynomial coefficients:

CISE 302 Lab Manual Page 15


16 Lab Experiment 1: Using MATLAB for Control Systems

>>p2 = poly(r)

p2 =
1 8.8818e-16 -2 -5

poly and roots are inverse functions,

Polynomial Evaluation
The polyval function evaluates a polynomial at a specified value. To evaluate p at s = 5, use

>>polyval(p,5)

ans =
110

It is also possible to evaluate a polynomial in a matrix sense. In this case the equation
( ) becomes ( ) , where X is a square matrix and I is the
identity matrix.

For example, create a square matrix X and evaluate the polynomial p at X:


>>X = [2 4 5; -1 0 3; 7 1 5];
>>Y = polyvalm(p,X)

Y=
377 179 439
111 81 136
490 253 639

Convolution and Deconvolution


Polynomial multiplication and division correspond to the operations convolution and
deconvolution. The functions conv and deconv implement these operations. Consider the
polynomials ( ) and ( ) . To compute their product,

>>a = [1 2 3]; b = [4 5 6];


>>c = conv(a,b)

c=
4 13 28 27 18

Use deconvolution to divide back out of the product:

>>[q,r] = deconv(c,a)

q=
4 5 6

r=
0 0 0 0 0

CISE 302 Lab Manual Page 16


17 Lab Experiment 1: Using MATLAB for Control Systems

Polynomial Derivatives
The polyder function computes the derivative of any polynomial. To obtain the derivative of
the polynomial

>>p= [1 0 -2 -5]
>>q = polyder(p)

q=
3 0 -2

polyder also computes the derivative of the product or quotient of two polynomials. For
example, create two polynomials a and b:

>>a = [1 3 5];
>>b = [2 4 6];

Calculate the derivative of the product a*b by calling polyder with a single output argument:

>>c = polyder(a,b)

c=
8 30 56 38

Calculate the derivative of the quotient a/b by calling polyder with two output arguments:

>>[q,d] = polyder(a,b)

q=
-2 -8 -2

d=
4 16 40 48 36

q/d is the result of the operation.

Partial Fraction Expansion


‘residue’ finds the partial fraction expansion of the ratio of two polynomials. This is
particularly useful for applications that represent systems in transfer function form. For
polynomials b and a,

( )
( )

if there are no multiple roots, where r is a column vector of residues, p is a column vector of
pole locations, and k is a row vector of direct terms.

Consider the transfer function


>>b = [-4 8];
>>a = [1 6 8];
>>[r,p,k] = residue(b,a)

CISE 302 Lab Manual Page 17


18 Lab Experiment 1: Using MATLAB for Control Systems

r=
-12
8

p=
-4
-2

k=
[]

Given three input arguments (r, p, and k), residue converts back to polynomial form:

>>[b2,a2] = residue(r,p,k)

b2 =
-4 8
a2 =
1 6 8

Exercise 1:

Consider the two polynomials ( ) and ( ) . Using


MATLAB compute
a. ( ) ( )
b. Roots of ( ) and ( )
c. ( ) and ( )

Exercise 2:

Use MATLAB command to find the partial fraction of the following


( )
a.
( )
( )
b.
( ) ( )

CISE 302 Lab Manual Page 18


19 Lab Experiment 1: Using MATLAB for Control Systems

Part III: Scripts, Functions & Flow Control in MATLAB

Objective: The objective of this session is to introduce you to writing M-file scripts,
creating MATLAB Functions and reviewing MATLAB flow control like ‘if-elseif-end’, ‘for
loops’ and ‘while loops’.

Overview:
MATLAB is a powerful programming language as well as an interactive computational
environment. Files that contain code in the MATLAB language are called M-files. You create
M-files using a text editor, then use them as you would any other MATLAB function or
command. There are two kinds of M-files:

 Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace. MATLAB provides a full programming language
that enables you to write a series of MATLAB statements into a file and then execute
them with a single command. You write your program in an ordinary text file, giving
the file a name of ‘filename.m’. The term you use for ‘filename’ becomes the new
command that MATLAB associates with the program. The file extension of .m makes
this a MATLAB M-file.
 Functions, which can accept input arguments and return output arguments. Internal
variables are local to the function.
If you're a new MATLAB programmer, just create the M-files that you want to try out in the
current directory. As you develop more of your own M-files, you will want to organize them
into other directories and personal toolboxes that you can add to your MATLAB search path.
If you duplicate function names, MATLAB executes the one that occurs first in the search
path.

Scripts:
When you invoke a script, MATLAB simply executes the commands found in the file.
Scripts can operate on existing data in the workspace, or they can create new data on which to
operate. Although scripts do not return output arguments, any variables that they create
remain in the workspace, to be used in subsequent computations. In addition, scripts can
produce graphical output using functions like plot. For example, create a file called
‘myprogram.m’ that contains these MATLAB commands:

% Create random numbers and plot these numbers


clc
clear
r = rand(1,50)
plot(r)

Typing the statement ‘myprogram’ at command prompt causes MATLAB to execute the
commands, creating fifty random numbers and plots the result in a new window. After
execution of the file is complete, the variable ‘r’ remains in the workspace.

CISE 302 Lab Manual Page 19


20 Lab Experiment 1: Using MATLAB for Control Systems

Functions:
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. Functions operate on variables
within their own workspace, separate from the workspace you access at the MATLAB
command prompt. An example is provided below:

function f = fact(n) Function definition line


% Compute a factorial value. H1 line
% FACT(N) returns the factorial of N, Help text
% usually denoted by N!

% Put simply, FACT(N) is PROD(1:N). Comment


f = prod(1:n); Function body

M-File Element Description


Function definition line Defines the function name, and the number and order of input and
(functions only) output arguments.
H1 line A one line summary description of the program, displayed when
you request help on an entire directory, or when you use
‘lookfor’.
Help text A more detailed description of the program, displayed together
with the H1 line when you request help on a specific function
Function or script body Program code that performs the actual computations and assigns
values to any output arguments.
Comments Text in the body of the program that explains the internal
workings of the program.

The first line of a function M-file starts with the keyword ‘function’. It gives the function
name and order of arguments. In this case, there is one input arguments and one output
argument. The next several lines, up to the first blank or executable line, are comment lines
that provide the help text. These lines are printed when you type ‘help fact’. The first line of
the help text is the H1 line, which MATLAB displays when you use the ‘lookfor’ command
or request help on a directory. The rest of the file is the executable MATLAB code defining
the function.

The variable n & f introduced in the body of the function as well as the variables on the first
line are all local to the function; they are separate from any variables in the MATLAB
workspace. This example illustrates one aspect of MATLAB functions that is not ordinarily
found in other programming languages—a variable number of arguments. Many M-files
work this way. If no output argument is supplied, the result is stored in ans. If the second
input argument is not supplied, the function computes a default value.

Flow Control:
Conditional Control – if, else, switch

This section covers those MATLAB functions that provide conditional program control. if,
else, and elseif. The if statement evaluates a logical expression and executes a group of
statements when the expression is true. The optional elseif and else keywords provide for the

CISE 302 Lab Manual Page 20


21 Lab Experiment 1: Using MATLAB for Control Systems

execution of alternate groups of statements. An end keyword, which matches the if,
terminates the last group of statements.
The groups of statements are delineated by the four keywords—no braces or brackets are
involved as given below.

if <condition>
<statements>;
elseif <condition>
<statements>;
else
<statements>;
end

It is important to understand how relational operators and if statements work with matrices.
When you want to check for equality between two variables, you might use

if A == B, ...

This is valid MATLAB code, and does what you expect when A and B are scalars. But when
A and B are matrices, A == B does not test if they are equal, it tests where they are equal; the
result is another matrix of 0's and 1's showing element-by-element equality. (In fact, if A and
B are not the same size, then A == B is an error.)

>>A = magic(4);
>>B = A;
>>B(1,1) = 0;
>>A == B
ans =
0 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

The proper way to check for equality between two variables is to use the isequal function:

if isequal(A, B), ...

isequal returns a scalar logical value of 1 (representing true) or 0 (false), instead of a matrix,
as the expression to be evaluated by the if function.
Using the A and B matrices from above, you get

>>isequal(A, B)
ans =
0

CISE 302 Lab Manual Page 21


22 Lab Experiment 1: Using MATLAB for Control Systems

Here is another example to emphasize this point. If A and B are scalars, the following
program will never reach the "unexpected situation". But for most pairs of matrices, including

if A > B
'greater'
elseif A < B
'less'
elseif A == B
'equal'
else
error('Unexpected situation')
end
our magic squares with interchanged columns, none of the matrix conditions A > B, A < B,
or A == B is true for all elements and so the else clause is executed:

Several functions are helpful for reducing the results of matrix comparisons to scalar
conditions for use with if, including ‘isequal’, ‘isempty’, ‘all’, ‘any’.

Switch and Case:


The switch statement executes groups of statements based on the value of a variable or
expression. The keywords case and otherwise delineate the groups. Only the first matching
case is executed. The syntax is as follows
switch <condition or expression>
case <condition>
<statements>;

case <condition>

otherwise
<statements>;
end

There must always be an end to match the switch. An example is shown below.

n=5
switch rem(n,2) % to find remainder of any number ‘n’
case 0
disp(‘Even Number’) % if remainder is zero
case 1
disp(‘Odd Number’) % if remainder is one
end

Unlike the C language switch statement, MATLAB switch does not fall through. If the first
case statement is true, the other case statements do not execute. So, break statements are not
required.

For, while, break and continue:


This section covers those MATLAB functions that provide control over program loops.

CISE 302 Lab Manual Page 22


23 Lab Experiment 1: Using MATLAB for Control Systems

for:
The ‘for’ loop, is used to repeat a group of statements for a fixed, predetermined number of
times. A matching ‘end’ delineates the statements. The syntax is as follows:

for <index> = <starting number>:<step or increment>:<ending number>


<statements>;
end

for n = 1:4
r(n) = n*n; % square of a number
end
r

The semicolon terminating the inner statement suppresses repeated printing, and the r after
the loop displays the final result.

It is a good idea to indent the loops for readability, especially when they are nested:

for i = 1:m
for j = 1:n
H(i,j) = 1/(i+j);
end
end

while:
The ‘while’ loop, repeats a group of statements indefinite number of times under control of a
logical condition. So a while loop executes atleast once before it checks the condition to stop
the execution of statements. A matching ‘end’ delineates the statements. The syntax of the
‘while’ loop is as follows:

while <condition>
<statements>;
end

Here is a complete program, illustrating while, if, else, and end, that uses interval bisection to
find a zero of a polynomial:

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end
x

CISE 302 Lab Manual Page 23


24 Lab Experiment 1: Using MATLAB for Control Systems

The result is a root of the polynomial x3 - 2x - 5, namely x = 2.0945. The cautions involving
matrix comparisons that are discussed in the section on the if statement also apply to the
while statement.

break:

The break statement lets you exit early from a ‘for’ loop or ‘while’ loop. In nested loops,
break exits from the innermost loop only. Above is an improvement on the example from the
previous section. Why is this use of break a good idea?

a = 0; fa = -Inf;
b = 3; fb = Inf;
while b-a > eps*b
x = (a+b)/2;
fx = x^3-2*x-5;
if fx == 0
break
elseif sign(fx) == sign(fa)
a = x; fa = fx;
else
b = x; fb = fx;
end
end

continue:
The continue statement passes control to the next iteration of the for loop or while loop in
which it appears, skipping any remaining statements in the body of the loop. The same holds
true for continue statements in nested loops. That is, execution continues at the beginning of
the loop in which the continue statement was encountered.

CISE 302 Lab Manual Page 24


25 Lab Experiment 1: Using MATLAB for Control Systems

Exersice 1: MATLAB M-file Script

Use MATLAB to generate the first 100 terms in the sequence a(n) define recursively by
( ) ( ) ( ( ))
with p=2.9 and a(1) = 0.5.

After you obtain the sequence, plot the sequence.

Exersice 2: MATLAB M-file Function

Consider the following equation

( ) ( √ )

a) Write a MATLAB M-file function to obtain numerical values of y(t). Your function
must take y(0), ζ, ωn, t and θ as function inputs and y(t) as output argument.
b) Write a second script m-file to obtain the plot for y(t) for 0<t<10 with an increment of
0.1, by considering the following two cases
Case 1: y0=0.15 m, ωn = √ rad/sec, ζ = 3/(2√ ) and θ = 0;
Case 2: y0=0.15 m, ωn = √ rad/sec, ζ = 1/(2√ ) and θ = 0;

Hint: When you write the function you would require element-by-element operator

Exersice 3: MATLAB Flow Control

Use ‘for’ or ‘while’ loop to convert degrees Fahrenheit (Tf) to degrees Celsius using the
following equation . Use any starting temperature, increment and ending
temperature (example: starting temperature=0, increment=10, ending temperature = 200).

Please submit the exercises (m-files and results) in the next lab.

CISE 302 Lab Manual Page 25

You might also like