You are on page 1of 110

LAB WORKBOOK

(BM-310) CONTROL SYSTEMS FOR BIOMEDICAL ENGINEERING

Name
Semester Fall Spring 20__
Roll No
Batch

NED UNIVERSITY OF ENGINEERING & TECHNOLOGY,


LEJ CAMPUS KARACHI-75270, PAKISTAN
LIST OF EXPERIMENTS
1. Introduction to the MATLAB environment and basic arithmetic calculations.

2. To explore the MATLAB data objects: matrices, arrays, vectors and sets and
operations applicable on these objects

3. To learn printing and plotting tools and graphics in MATLAB

4. To learn methods the flow of programming in MATLAB through loops.

5. To learn to use MATLAB to (1) generate polynomials, (2) manipulate polynomials,


(3) perform partial-fraction expansions. (4) find Laplace transforms for time
functions and, (5) find time functions from Inverse Laplace transforms

6. To learn to use MATLAB to (1) generate transfer functions, (2) manipulate transfer
functions, (3) identifying poles and zeros of transfer functions (4) plotting poles
and zeros of transfer functions (5) To study model conversion techniques

7. To learn the modeling of physical systems using Simulink

8. Learning simulation of linear systems with Unit Step and Impulse Inputs

9. OEL: Mathematical Modeling and Simulation of a control system with different


Inputs

10. To learn commands in MATLAB that would be used to reduce linear systems
block diagram using series, parallel and feedback configuration.

11. To study the performance characteristics of First order systems using MATLAB

12. To study the performance characteristics of Second order systems using MATLAB
COMMITMENT CHART
Week No. of
Date Object Sign
No Sessions
1. Introduction to the MATLAB environment and basic arithmetic
calculations.

2. To explore the MATLAB data objects: matrices, arrays, vectors


and sets and operations applicable on these objects

3. To learn printing and plotting tools and graphics in MATLAB

4. To learn methods the flow of programming in MATLAB


through loops.

5. To learn to use MATLAB to (1) generate polynomials, (2)


manipulate polynomials, (3) perform partial-fraction
expansions. (4) find Laplace transforms for time functions and,
(5) find time functions from Inverse Laplace transforms

6. To learn to use MATLAB to (1) generate transfer functions, (2)


manipulate transfer functions, (3) identifying poles and zeros of
transfer functions (4) plotting poles and zeros of transfer
functions (5) To study model conversion techniques

7. To learn the modeling of physical systems using Simulink

8. Learning simulation of linear systems with Unit Step and


Impulse Inputs

9. OEL: Mathematical Modeling and Simulation of a control


system with different Inputs

10. To learn commands in MATLAB that would be used to reduce


linear systems block diagram using series, parallel and feedback
configuration.

11. To study the performance characteristics of First order systems


using MATLAB

12. To study the performance characteristics of Second order


systems using MATLAB
EVALUATION SHEET
Class Learning Outcome (CLO)
CLO PLO T
Demonstrate the concept of system modeling, system performance system stability and 5 P
system response analysis using modern tools 2

Rubrics for Lab Manual Assessment

OUTSTANDING ACCOMPLISHED DEVELOPING BEGINNER


CATEGORY
10 8 5 2

Need minimal Need moderate


Develops Unable to
Understanding guidance to level of guidance
understanding about understand the
understand the to understand the
concept of basic idea of
concept of concept of
experiment, experiment
experiment experiment
Always select Sometimes
Mostly identify
Selection of appropriate identify the
the required tool Do not select
component/ source component for required tool for
for achieving the right tools
code achieving the achieving the
objectives
objectives objectives
Operating
Clearly demonstrate Operating
procedure
the operating procedure Does Not explain
Operating Procedure described is
procedure of the described is at all
somewhat
machine acceptable
acceptable
Obtains the results
Obtains the
correctly with Obtains the
results but with Unable to obtain
Results Interpretation complete and results without
minimal results.
meaningful inferences.
inferences
inferences
Rubrics for Open Ended Lab

Grade Allocation
Rubric
A B C D
Demonstrates a
Demonstrates a Demonstrates Demonstrates
Contextualize Problem: comprehensive
clear some no
and insightful
Ability to understand the understanding understanding understanding
understanding
problem within a larger of how the of how the of how the
of how the
context (problem within a problem fits problem fits problem fits
problem fits
problem). within the within the within the
within the
larger context. larger context. larger context.
larger context.
Demonstrates a
skillful ability Demonstrates
to identify Demonstrates some ability to Demonstrates
multiple an ability to identify a minimal or no
Formulate Strategies for strategies for identify an strategy for ability to
generating appropriate generating an identify a
Solving a Problem:
approaches to strategy for approach for strategy for
Ability to identify strategies solve a generating solving the generating an
for solving problems problem, and approaches for problem. approach for
has insight into solving a Strategy may or solving a
the pros and problem. may not be problem.
cons of those appropriate.
strategies
Demonstrates a Demonstrates
Demonstrates Demonstrates
skillful ability minimal or no
an ability to some ability to
to analysis, ability to
Analyze, Evaluate and Select analyze, analyze,
evaluate and analyze,
evaluate and evaluate and
Solutions: select evaluate or
select select
optimal/practic select
Ability to analyze, evaluate optimal/practic optimal/practic
al solution. optimal/practic
and select optimal/practical al solution. al solution.
Thorough and al solution.
solution, including feasibility Clear Partial
insightful Little or no
and impact. explanation of explanation of
explanation of explanation of
feasibility and feasibility and
feasibility and feasibility and
impact. impact.
impact. impact.
Implement Solutions: Demonstrates a Demonstrates Demonstrates Demonstrates
skillful ability an ability to some ability to minimal or no
ability to
Ability to implement a to implement a implement a implement a
implement a
practical solution to address practical practical practical
practical
the problem. solution solution. solution.
solution.

Learning by doing is probably the most effective way to maximize


retention. Remember!
I hear and I forget
I see and I remember
I do and I understand
~Confucius
1 Lab 01
Object
Introduction to the MATLAB environment and basic arithmetic calculations.
1.1 Introduction
This lab is a brief introduction to MATLAB (an abbreviation of MATrix LABoratory) basics,
registered trademark of computer software, version 4.0 or later developed by the Math Works Inc. The
software is widely used in many of science and engineering fields. MATLAB is an interactive program
for numerical computation and data visualization. MATLAB is supported on Unix, Macintosh, and
Windows environments.

MATLAB integrates mathematical computing, visualization, and a powerful language to provide a


flexible environment for technical computing. The open architecture makes it easy to use MATLAB and
its companion products to explore data, create algorithms, and create custom tools that provide early
insights and competitive advantages.
Known for its highly optimized matrix and vector calculations, MATLAB offers an intuitive language
for expressing problems and their solutions both mathematically and visually. Typical uses include:
● Numeric computation and algorithm development

● Symbolic computation (with the built-in Symbolic Math functions)

● Modeling, simulation, and prototyping

● Data analysis and signal processing

● Engineering graphics and scientific visualization

In the subsequent labs, we will introduce the MATLAB environment. We will learn:
1. How to create, edit, save, run, and debug m-files (ASCII files with series of MATLAB statements).
2. How to create arrays (matrices and vectors), and explore the built-in MATLAB linear algebra
functions for matrix and vector multiplication, dot and cross products, transpose, determinants, and
inverses, and for the solution of linear equations.
3. How to program logic constructs and loops in MATLAB,
4. How to use subprograms and functions,
5. How to use comments (%) for explaining the programs and tabs for easy readability, and
6. How to print and plot graphics both two and three dimensional.
7. Additionally, we will explore MATLAB’s functions for symbolic mathematics and the use of these
functions to perform symbolic operations, to develop closed form expressions for solutions to
algebraic equations, ordinary differential equations, and system of equations was presented.
Symbolic mathematics can also be used to determine analytical expressions for the derivative and
integral of an expression.

1.1.1 MATLAB Desktop


Once MATLAB® is installed, it is time to start using it. MATLAB is best understood by entering the
instructions in your computer one at a time and by observing and studying the responses.

Figure 1.1 A representation of the working environment of MATLAB

The desktop includes three main panels:


1) Current Folder — Access your files.
2) Command Window — Enter commands at the command line, indicated by the prompt (>>).
3) Workspace — Explore data that you create or import from files.

1.1.2 Starting and Quitting MATLAB


To start MATLAB, click on the MATLAB icon or type in MATLAB, followed by pressing the enter or
return key at the system prompt. The screen will produce the MATLAB prompt “>>”, which indicates
that MATLAB is waiting for a command to be entered. In order to quit MATLAB, type quit or exit after
the prompt, followed by pressing the enter or return key.
1.1.3 Display Windows
MATLAB has three display windows. They are
1. A Command Window which is used to enter commands and data to display plots and graphs.
2. A Graphics Window which is used to display plots and graphs
3. An Edit Window which is used to create and modify M-files. M-files are files that contain a program
or script of MATLAB commands.

1.1.4 Entering Commands


Every command has to be followed by a carriage return <cr> (enter key) in order that the command can
be executed. MATLAB commands are case sensitive and lower-case letters are used throughout.
To execute an M-file (such as Project_1.m), simply enter the name of the file without its extension (as in
Project_1).

1.1.5 MATLAB Expo


In order to see some of the MATLAB capabilities, enter the demo command. This will initiate the
MATLAB EXPO. MATLAB Expo is a graphical demonstration environment that shows some of the
different types of operations which can be conducted with MATLAB.

1.1.6 Abort
In order to abort a command in MATLAB, hold down the control key and press c to generate a local
abort with MATLAB.

1.1.7 The Semicolon (;)


If a semicolon (;) is typed at the end of a command the output of the command is not displayed.

1.1.8 Typing %
When percent symbol (%) is typed in the beginning of a line, the line is designated as a comment. When
the enter key is pressed the line is not executed.

1.1.9 The clc Command


Typing clc command and pressing enter cleans the command window. Once the clc com- mand is
executed a clear window is displayed.

1.1.10 Help
MATLAB has a host of built-in functions. For a complete list, refer to MATLAB user’s guide or refer to
the on-line Help. To obtain help on a particular topic in the list, e.g., inverse, type help inv.

1.1.11 Statements and Variables


Statements have the form
>> variable = expression
The equals (“=”) sign implies the assignment of the expression to the variable. For instance, to enter a 2
× 2 matrix with a variable name A, we write
>> A = [1 2; 3 4] <ret>
A=
1 2
3 4

1.2 Arithmetic Operations


Table 1.1 Arithmetic Symbols and their syntax in MATLAB

1.3 Display Formats


MATLAB has several different screen output formats for displaying numbers. These formats can be
found by typing the help command: help format in the Command Window. A few of these formats are
shown in Table 1.2 for 2π.
Table 1.2 Display Formats in MATLAB
1.4 Elementary Built-In MATLAB Functions
Table 1.3 Common Mathematic Functions in MATLAB

Table 1.4 Trigonometric Functions

Table 1.5 Complex Number Functions


1.5 Variable Names
A variable is a name made of a letter or a combination of several letters and digits. MATLAB is case
sensitive. For instance, XX, Xx, xX, and xx are the names of four different variables. It should be noted
here that not to use the names of a built-in functions for a variable. For instance, avoid using: sin, cos,
exp, sqrt, ..., etc. Once a function name is used to define a variable, the function cannot be used.
1.6 Pre-Defined Variables
Table 1.6 Pre-defined variables in MATLAB

Table 1.7 Termination Operators in MATLAB


Table 1.8 Managing Variables in MATLAB

1.7 Always Seek Help!


The help command is a major source of information regarding any function being used in programming.
Getting acquainted and using help or the help documentation can help a programmer avoid unnecessary
delays. Here are some examples:

help lists all primary help topics in the Command Window. Each main help topic corresponds to a
directory name on the MATLAB search path.

help functionname This command displays a description of the function and generally also includes a
list of related functions. If you cannot remember the name of the function, use the ‘lookfor’ command
and the name of some keyword associated with the function.

help toolbox/ displays the contents file for the specified directory named toolbox. It is not necessary to
give the full pathname of the directory; the last component, or the last several components, are
sufficient.

help toolbox/function displays the M-file help for function that belongs to the toolbox directory.

help syntax displays M-file help describing the syntax used in MATLAB commands and functions.

help whos displays documentation for the function whos

lookfor keyword This command will display a list of functions that include the keyword in their
descriptions. Other help commands that you may find useful are ‘info’, ‘what’, and ‘which’.
Descriptions of these commands can be found by using the help command.

1.8 Function and Script Files


MATLAB files with extension m are referred to as M-files. MATLAB uses two types of M-files: script
and function files. Script and function files should be saved in the current folder (default), which is
available when working in the MATLAB domain.
The content of a script file may be a program, data, or just a set of instructions that are created using the
Edit/Debugger built into MATLAB. The edit window can be accessed in the MS Windows environment
by the following sequence of actions; once in the command window: File → New → M −File.

A program can then be typed using the MATLAB word-processor software and keyboard. When typing is complete

Script files are used to process a sequence of commands that are stored in the computer memory by
typing just one word—the file’s name. The file is then executed without any display at the command
window; unless the echo command is activated, or a command ends with a comma, or a required output
is programmed.
A function file is created following the same sequence of steps outlined for the script fi les, but the first
line follows the syntax
function [output_variables] = function_name(input_variables)

where the input_variables are local, which means that their values can be used only within the function
file.
A function file can be called by typing the following at the command window:
[output_variables] = function_name(input_variables)

Function files evaluate and return the output_variables given the input_variables.
Lab Exercise 01
1) Evaluate the following mathematical expressions by transforming them into MATLAB (notation)
and estimate the values of x and y, respectively, by hand using the operational hierarchy, then use
MATLAB, and verify the results obtained by hand.
a) x=4+2 − √ ❑
3

2 2
b) y=1+ 3 −4
( √❑ )

Analytical Solution (a) Analytical Solution (b)

MATLAB Solution (a) MATLAB Solution (b)

2) The following MATLAB program was written to evaluate the hypotenuse of a right triangle with
sides A = 4 and B = 3. Fill out the missing comments for a better understanding of the code.
>>A = 3; % _____________________________________________________
>>B = 4; % _____________________________________________________
>>C = sqrt(A^2+B^2); % _________________________________________
>> Hypotenuse = C; % ___________________________________________
What would be the final output displayed on the screen? (Write in the exact same format as
shown on the screen)
_____________________________________________________________________________
3) Write down the correct syntax and the associated outputs for the following:
3
c=ln (e )+ ln(e )

Syntax

Output

d=log (e )+ log ( e 3 )

Syntax

Output
e=π

Syntax

Output

f =cos ( π4 )
Syntax

Output
3 √❑
g=e

Syntax

Output

h=log ( 5 ) + ( 5 ) + log 2 5

Syntax
Output

4) Use the format long and short specifiers to compare between the outputs of the following:

Command Format Long Format Short

a = pi

b = eps

c = a+b

d = realmax

e = realmin

f = intmax

flops

date

clock

cputime

computer

ver

beep

license

Also %comment on the function being performed in each command.

Command Function

a = pi

b = eps

c = a+b
d = realmax

e = realmin

f = intmax

flops

date

clock

cputime

computer

ver

beep

license
Problems
Construct the following programs and show the complete syntax and associated output on a separate A4
sheet.

1) A $314 coat has a discount of 30%. What is the price of the coat?
2) A student gets 9 questions right on a 20-question test.
a. Write a MATLAB program that returns the percentage of correct answers.
b. What should the student’s grade be if three questions are worth 5%, two are worth 6%, and the
remaining four are worth 7%?

3) A triangle with side lengths a, b, and c is given. The area A is given by Hero’s formula as A=√ ❑,
a+ b+c
where s= . Write a MATLAB program that returns the area for the following triangles with
2
side lengths 5, 7, and 9.
4) Three points given in terms of the Cartesian coordinates system define a triangle. Write a program to
compute the area of the triangle if the vertex points are given by the following points:
P1 (1 ,1), P 2(2, 4),∧P3 (3 , 2)

5) Write a MATLAB program that estimates your electric bill, if the appliances with the kilowatt
consumption are shown in the Table below and the cost per kilowatt-hour of usage charge by the
power provider is $0.13.
Kilowatt hours used (during a month) * cost (per kilowatt hour) = total cost in dollars ($) per
month
2 Lab 02
Object
To explore the MATLAB data objects: matrices, arrays, vectors and sets and operations applicable on
these objects
Introduction
An array is a list of numbers arranged in rows and/or columns. A one-dimensional array is a row or a
column of numbers and a two-dimensional array has a set of numbers arranged in rows and columns. An
array operation is performed element-by-element.
2.1 Row Vector
A vector is a row or column of elements.
In a row vector the elements are entered with a space or a comma between the elements inside the
square brackets. For example,
x = [7 – 1 2 – 5 8]

2.2 Column Vector


In a column vector the elements are entered with a semicolon between the elements inside the square
brackets. For example,
x = [7; – 1; 2; – 5; 8]

2.3 Matrix
The basic element in MATLAB® is the matrix. A matrix is a two-dimensional array which has numbers
in rows and columns. A matrix is entered row-wise with consecutive elements of a row separated by a
space or a comma, and the rows separated by semicolons or carriage returns. The entire matrix is
enclosed within square brackets. The elements of the matrix may be real numbers or complex numbers.
For example, to enter the matrix
A=[ 1 3 4 0−2 8 ]
The MATLAB input command is
A = [1 3 –4; 0 – 2 8]

Similarly, for complex number elements of a matrix B


[ −5 x ln2 x+ 7 sin 3 y 3 i5−13 i ]
The MATLAB input command is

B=[ −5∗x log log ( 2∗x ) +7∗sin sin ( 3∗y ) ; 3 i5−13 i ]


2.4 Taking input from the user at Runtime
When the command A = input(‘expression’) is run, it simply evaluates the expression (in
quotes) and waits for an input from the user. The inputted number is used to find the result which is
assigned to A. If the return key is pressed without entering a character, then A becomes an empty
matrix. The empty matrix can be defined as a matrix with no elements.
The input statement can also be used to enter a string such as
B = input (‘Enter a string’, ‘s’)
This instruction will display Enter a string (whatever is in quotes) and MATLAB will wait for the
user to enter a string. That string will be assigned to B. A string can be defined as a sequence of
characters.
2.5 Addressing Arrays
A colon can be used in MATLAB to address a range of elements in a vector or a matrix.
2.6 Colon for a vector
Colons can also be used to generate a sequence. For example, n = 1:5 returns the vector n, consisting of
the sequence of elements from 1 to 5 in ascending order, with unit increments. Then n becomes a 1 × 5
(row) vector indicated as follows:
n = [1 2 3 4 5]

When a command has two colons that separate three numerical arguments, following the format:
n = [initial: increment: final]

then the command returns the vector n, with elements that follow the sequence It starts with the initial
value all the way to the final value, with successive increments defined by increment, illustrated as
follows:
n = [1:0.1:2], returns the following sequence

n = [1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0]

The preceding sequence can also be generated without the brackets or by replacing the brackets with
parenthesis. For example,
n = 1:0.1:2 is equivalent to n = [1:0.1:2] and n = (1:0.1:2)

Note that the increment variable when negative is used to generate a decreasing sequence, illustrated as
follows:
>> n = 2:-0.1:1

n =

Columns 1 through 7
2.0000 1.9000 1.8000 1.7000 1.6000 1.5000 1.4000
Columns 8 through 11

1.3000 1.2000 1.1000 1.0000

Additionally, a multiple line command that starts in one line is continued on the next line by placing
three consecutive periods (…) called ellipsis at the end of the first line. Continuation across several lines
can be accomplished by using ellipsis repeatedly at the end of each line, but no instruction should
exceed 4096 characters.
The elements of different vectors or matrices can be concatenated to form new extended vectors or
matrices. The extended matrix is defined in terms of other vectors or matrices. For example,
let u = [0 1] and v = [2 3].

Then, evaluate:
s = [u v]

ss = [u; v]

sss = [ss, ss; ss, ss]

The same concept is applicable to matrices as well.


Vector Indexing
let s = [0 1 2 3] The elements of a vector are identified by a single index. For example,
s(3) = 2 or s(end-1) = 2

Any element can be changed by redefining it with a new value. For example,

let s(4) = 1 (is entered), then vector s becomes s = [0 1 2 −1]

Defining an element outside its range can be used to expand the range or length of a matrix or vector. For example, b

s = [0 1 2 −1 0 −2]

The elements not specifically defined in a vector or matrix are assigned the default value of zero.
Observe that in s, s(5) = 0.

A set of rows or columns can be deleted by using the null vector ([ ]). For the vector s defined above, the instruction
s = [s(1) s(5)
s(6)]

An alternate way to generate a sequence n that is a row vector is by using the command:
linspace(initial, final, m_points),

where initial and final correspond to the start and end of the sequence, respectively, defined by m points,
equally spaced over the range initial/final.
For example, n = linspace(1, 2, 11) returns the sequence

n = [1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0]

Additionally, the syntax V(:) – refers to all the elements of the vector V (either a row or a column
vector). Whereas V(m : n) – refers to elements m through n of the vector V. For instance
>>V = [2 5 –1 11 8 4 7 –3 11]
>>u = V (2:8)
u = 5 –1 11 8 4 7 –3 11
Colons when used as an argument identify a range over a row or a column depending on its location.
For example,
if A=[ 1 4 7 2 58 3 6 9 ]
B= A ( 1 :2 ,2 :3 ) =[ 4 7 5 8 ]
2.7 Colon for a Matrix
Table 2.1 Indexing Elements from a matrix

2.8 Adding Elements to a Vector or a Matrix


A variable that exists as a vector, or a matrix, can be changed by adding elements to it. Addition of
elements is done by assigning values of the additional elements, or by appending existing variables.
Rows and/or columns can be added to an existing matrix by assigning values to the new rows or
columns.
2.9 Deleting Elements
An element, or a range of elements, of an existing variable can be deleted by reassigning blanks to these
elements. This is done simply by the use of square brackets with nothing typed in between them.
2.10 Built-in Functions
Some of the built-in functions available in MATLAB for managing and handling arrays as listed in
Table below
Table 2.2Built-In Functions of MATLAB
2.11 Operations on Arrays
We consider here matrices that have more than one row and more than one column.
2.11.1 Addition and Subtraction of Matrices
The addition (the sum) or the subtraction (the difference) of the two arrays is obtained by adding or
subtracting their corresponding elements. These operations are performed with arrays of identical size
(same number of rows and columns).
For example, if A and B are two arrays (2 × 3 matrices).

Then, the matrix addition (A + B) is obtained by adding A and B is

2.11.2 Dot Product


The dot product is a scalar computed from two vectors of the same size. The scalar is the sum of the
products of the values in corresponding positions in the vectors.
For n elements in the vectors A and B:

n
dot product = A • B=∑ ai bi
i=1

dot(A, B) Computes the dot product of A and B. If A and B are matrices, the dot product is a row
vector containing the dot products for the corresponding columns of A and B.

2.11.3 Array Multiplication


The value in position ci, j of the product C of two matrices, A and B, is the dot product of row i of the
first matrix and column of the second matrix:
n
c i , j=¿ ∑ ai ,k b k , j
k =1

2.11.4 Identity Matrix


An identity matrix is a square matrix in which all the diagonal elements are 1’s, and the remaining
elements are 0’s. If a matrix A is square, then it can be multiplied by the identity matrix, I, from the left
or from the right:
AI =IA =A
It can be generated using the command eye(n) where n is the order of the square matrix.

2.11.5 Inverse of a Matrix


The matrix B is the inverse of the matrix A if when the two matrices are multiplied the product is the
identity matrix. Both matrices A and B must be square and the order of multiplication can be AB or BA.
AB=BA=I
It can be evaluated using the command inv(A) where A is a variable in which a square matrix is
stored.

2.11.6 Transpose
The transpose of a matrix is a new matrix in which the rows of the original matrix are the columns of the
new matrix. The transpose of a given matrix A is denoted by A T. In MATLAB, the transpose of the
matrix A is denoted by A′.

2.11.7 Determinant
A determinant is a scalar computed from the entries in a square matrix. For a 2 × 2 matrix A, the
determinant is
| A|=a 11 a22 – a21 a12

MATLAB will compute the determinant of a matrix using the det function:

det(A) computes the determinant of a square matrix A.

2.11.8 Array Division


MATLAB has two types of array division, which are the left division and the right division.

Left Division
The left division is used to solve the matrix equation Ax = B where x and B are column vectors.
Multiplying both sides of this equation by the inverse of A, A–1, we have

−1 –1
A Ax=A B
−1
¿ I . x=x= A B
Hence, x= A−1 B

In MATLAB, the above equation is written by using the left division character: x = A \ B

Right Division
The right division is used to solve the matrix equation xA = B where x and B are row vectors.
Multiplying both sides of this equation by the inverse of A, A–1, we have
–1 –1
x • A A =B• A
¿ x=B • A
In MATLAB, this equation is written by using the right division character: x = B \ A

2.11.9 Eigenvalues and Eigenvectors


Consider the following equation,
AX=λX
Where A is an n × n square matrix, X is a column vector with n rows and λ is a scalar.
The values of λ for which X are nonzero are called the eigenvalues of the matrix A, and the
corresponding values of X are called the eigenvectors of the matrix A.
( A – λI ) X=0
where I is an n × n identity matrix. The above equation is corresponding to a set of homogeneous
equations and has nontrivial solutions only if the determinant is equal to zero, or
¿ A – λI ∨¿ 0
The above equation is known as the characteristic equation of the matrix A. The solution of this equation
gives the eigenvalues of the matrix A.

MATLAB determines both the eigenvalues and eigenvectors for a matrix A.


eig(A) Computes a column vector containing the eigenvalues of A.
[Q, d] = eig(A) Computes a square matrix Q containing the eigenvectors of A as columns and a
square matrix d containing the eigenvalues (λ) of A on the diagonal. The values of Q and d are such that
Q * Q is the identity matrix and A * X equals λ times X.

2.12 Element-by-Element Operations


Element-by-element operations can only be done with arrays of the same size. Element-by-element
multiplication, division, and exponentiation of two vectors or matrices is entered in MATLAB by typing
a period in front of the arithmetic operator. Table below lists these operations.
2.12.1 Built-in Functions for Arrays
The table below lists some of the many built-in functions available in MATLAB for analyzing arrays.
Table 2.3 The common built-in functions applicable on arrays in MATLAB

2.13 Random Number Generator


There are many physical processes and engineering applications that require the use of random numbers
in the development of a solution.
MATLAB has two commands rand and randn that can be used to assign random numbers to variables.
The rand command: The rand command generates uniformly distributed over the interval [0, 1]. A seed
value is used to initiate a random sequence of values. The seed value is initially set to zero. However, it
can be changed with the seed function.
The command can be used to assign these numbers to a scalar, a vector, or a matrix, as shown in Table

MATLAB will generate Gaussian values with a mean of zero and a variance of 1.0 if a normal
distribution is specified. The MATLAB functions for generating Gaussian values are as follows:
randn(n) Generates an n × n matrix containing Gaussian (or normal) random numbers with a mean of
0 and a variance of 1.
Randn(m, n) Generates an m × n matrix containing Gaussian (or normal) random numbers with a
mean of 0 and a variance of 1.
Lab Exercise 02
1) Do as Directed and write down the output obtained:
a) >>A= input (‘Enter the MATLAB expression’) and find sqrt(pi)

b) >>My _ name _ is = input (‘Enter your name’,’s’)

c) >>My _ name _ is = input (‘Enter your name’) %Don’t input anything!

d) >> My _ name _ is = input (‘Enter your name’) %Input a name without


quotes

e) >> My _ name _ is = input (‘Enter your name’) %Input a name with


quotes

f) >> format compact


>> A = [1 2; 3 4]

g) Let, A=[ 1 2 3 4 ] ∧B=[ 6 7 8 9 ] then, find:


i) C = A+B
ii) D = A.*B
iii) E=A./B
iv) F=A.\B
v) G=A-B
vi) H=A.^B
vii) I = A.^2
h)
Create a vector over the range of X be over 2 X 4, consisting of eight linearly spaced points organize as a 2

i) Let V =[13 0.1 8 5 1213 6 3.9−9 1.3−5.4 0.213.8]


j) Execute and observe the responses of the following commands using MATLAB and comment on
the outputs:
i) Y = sum(V)
ii) Z1 = prod(V)
iii) Vmax = max(V)
iv) [maxv, indexmax] = max(V)
v) Vmin = min(V)
vi) [minv, indexmin] = min(V)
vii) Y1= Sort(V)
viii) [y, z] = sort(V)
ix) A=[ 01 2 3 4 5 6 7 8 ] , ∑ ( A)
x) B=[ 1 23 4 0 3−4 5 4 7 8 9−3−5 0.7 5 ] , sortrows (B)
xi) sort ¿

Output Comment

i.

ii.

iii.
iv.

v.

vi.

vii.

viii.

ix.

x.

xi.
Problems
1) Evaluate and give a descriptive comment next to each instruction of the following program:
a) X = [-10:1:10]
b) A = eye(length(x))
c) B = fix(rand(size(A))
d) C = zeros(size(A)) + B
e) D = tril(ceil(rand(4)))
f) E = tril(fix(5*randn(4)))
g) F = diag(d).* diag(E)
2) Create the following matrices using MATLAB:

Determine using MATLAB commands


a) Size of A and B
b) Rank of A and Determinant of A
c) Transpose of A and Trace of A
d) Inverse of A
e) Maximum and minimum values of the elements in C
f) Append B to A to return a 3 × 5 matrix
g) Create a 3 × 2 array D, consisting of all the elements in the first two columns of A

3) Execute the following MATLAB command: x = 10 * rand(1, 20) and record vector x.
Write a set of MATLAB commands that return
a) The maximum value of x and the minimum value of x
b) The sum of all the elements of x and the product of all the elements of x
c) The average value of the elements of x and the median value of the elements of x
d) The size of x
e) Identify and display the value of the 7th element of x
f) Rearrange the values of x in ascending and descending order

4) Enter the MATLAB command x = rand(1, 100) that returns a row vector consisting of 100
random elements. Write a MATLAB program that adds all the elements of x with even indexes
indicated by the following equation:
3 Lab 03
Object
To learn printing and plotting tools and graphics in MATLAB
3.1 Introduction
Graphic capabilities are quite important in engineering, social science, natural science, education,
behavioral science, health, economy, weather, production (growth and decay), politics, biology,
accounting, and business, just to mention a few and diverse disciplines. Graphs are an important way to
communicate and visualize trends and patterns that are otherwise difficult to identify, and gain valuable
insight into a given relation or problem in this way. Information when given in the form of tables can be
easily graphed and be used to make educated predictions and decisions.
A graph, like an equation, is the language that best helps recognize the relationship, which exists
between the variables involved in a situation. The 2-D Cartesian system is the most frequently used
system by engineers and scientists. MATLAB® offers its users simple and easy-to-use graphic
commands to obtain 2-D and 3-D plots in the Cartesian coordinate system as well as in other systems.
In general, a plot can be constructed once a relation in the form of a table exists between x and y. This
relation is frequently expressed by vectors (or matrices) in MATLAB. The command plot (x, y) is
the most popular plotting command used in MATLAB, and MATLAB returns the plot of the points
defined by <xi, yi> for all is connected by straight.
3.2 Printing Formats
The command disp(‘text’) is used to display the string vector text that is enclosed in quotes, inside
parenthesis. For example, display the string: This is a string text.
MATLAB Solution
>> format compact

>> text = ‘This is a string text ’ ;

>> disp (text)

This is a string text

The numerical value of a variable can be displayed by using the command


disp(variablename).

For example, display the values of x = 1, π, and e.


MATLAB Solution
>> x =1;
>> disp(x)

>> disp(pi)

3.1416

>> disp(exp(1))

2.7183

Strings texts and variables can be displayed in a text like format using the command disp([‘text’]),
as long as the argument of disp, the text is a string. A numerical variable can be converted to a character
string using the command num2str(x) or int2str(x), where x is either a number or an integer.

For example, evaluate the values of e and π, and then display each one of the integrated messages.
a. The value of e is ????, and pi = ?????
b. The value of e as an integer is ?????
MATLAB Solution

>> format compact

>> x = exp(1) % number

x =

2.7183

>> y = num2str (x) % string

y =

2.7183

>> z = pi % number

z =

3.1416

>> v = num2str(z) % string

v =

3.1416

>> disp ([‘The value of e is ‘,y,’, and pi = ‘,z’])


The value of e is 2.7183, and pi = 3.1416.

>> w = int2str(x)

w =

>> disp ([‘The value of e as integer is ’,w,]) % note that the integer

value of 2.718 … is 3

The value of e as an integer is 3

An alternate way to display an integrated text consisting of strings and numerical values represented by
variables is by using the commands: fprintf(‘text ’,’control’, variables), or sprintf(‘text’, ‘ control’,
variables), where text is the string that will be displayed and control defines the format of the output
variables.
For example, use the commands fprintf and sprintf to display the following integrated messages:
a. The value of e is ???????, to six decimal places using an eight-character field.
b. Today is ?????, using the standard MATLAB command.
MATLAB Solution

>> fprintf (‘The value of e = %8.6f \n’, exp (1))

The value of e = 2.718282

>> fprintf (‘Today is %s \n’, date)

Today is 01-Mar-2021

>> sprintf (‘The value of e is %8.6f \n’, exp (1)) % observe that

the response includes ans

ans =

The value of e is 2.718282

>> sprintf (‘Today is %s \n’, date)

ans =

Today is 01-Mar-2021
The special sequence \n, \r, \t, \b, \f can be used to produce linefeed, carriage return,
tab, backspace, and feed character, respectively.
3.3 Plotting in MATLAB
The most common 2-D command used for plotting is the command plot(x, y). Recall that a number
is graphed on a single line. The horizontal axis is referred to as the x-axis, and the vertical axis is the y-
axis. To graph y versus x means to make a drawing that represents its solution. In order to use the
command plot(x, y), the variables x and y must be stored as two separate arrays of ordered numbers in
sequential order. The plot command can be executed if and only if the arrays x and y have the same
length (number of elements). The resulting plot may not be smooth, unless a sufficiently large number of
points are employed.
The basic command for producing a custom 2-D plot can also be written as
plot(x values, y values, ‘style option’)

where, x values and y values are vectors containing the x- and y-coordinates of points on the graph.
Style option is an optional argument that specifies the color, line-style, and the point marker style. The
style option in the plot command is a character string that consists of 1, 2, or 3 characters that specify the
color and/or the line style.
There are three ways of generating overlay plots in MATLAB, they are:
(a) Plot command
(b) Hold command
(c) Line command
(a) Plot command. Example below shows the use of plot command used with matrix argument, each
column of the second argument matrix plotted against the corresponding column of the first argument
matrix.
(b) Hold command. Invoking hold on at any point during a session freezes the current plot in the
graphics window. All the next plots generated by the plot command are added to the exiting plot. See
Example below.
(c) Line command. The line command takes a pair of vectors (or a triplet in 3–D) followed by a
parameter name / parameter value pairs as argument. For instance, the command: line (x data, y data,
parameter name, parameter value) adds lines to the existing axes.
Practice Plotting:

Plot the trigonometric function f(x) = y = 1.5 cos(2x), over the domain 0 x 2, using 5, 10, 15, and 20 points, and the

MATLAB Solution

>> x5 = linspace(0,2*pi,5); % x5 is defined by 5 points and 4 segments

>> y5 = 1.5*cos(2.*x5);

>> plot(x5,y5)

>> x10 = linspace(0,2*pi,10); % x10 is defined by 10 points and 9 segments

>> y10 = 1.5*cos(2.*x10);

>> plot(x10,y10)

>> x15 = linspace(0,2*pi,15); % x15 is defined by 15 points and 14 segments

>> y15 = 1.5*cos(2.*x15);

>> plot(x15,y15)

>> x20 = linspace(0,2*pi,20); % x20 is defined by 20 points and 19 segments

>> y20 = 1.5*cos(2.*x20);

>> plot(x20,y20)
Use MATLAB to obtain overlay plots of the following functions: [y1 = 2.5 cos(x)] versus x and [y2 = 3.5 sin(x)] ve

MATLAB Solution

>> x = linspace(0,2*pi,50); % x defines 50 points linearly spaced over 0 ≤


x≤ 2π

>> y1 = 2.5*cos(x); % y1 are the 50 values for x

>> y2 = 3.5*sin(x); % y2 are the 50 values for x

>> plot(x,y1) % plot [2.5cos(x)] vs. x

>> hold on % holds the graph

>> plot(x,y2) % plot [3.5sin(x)] vs. x

Or

>> plot(x,y1, x,y2) % you can plot them together!


Multiple Plots
Multiple plots can be obtained by using the command plot(Y), where Y is an m × n matrix. MATLAB
returns n plots, one for each of the n columns of Y versus its index. MATLAB returns the plots color
coded with the first plot represented by blue, the second by green, the third by red, etc. Additonally, The
command plotyy(x, f1(x), x, f2(x)) returns the plots of two different functions: f1(x) versus
x, and f2(x) versus x over the same (x) domain, but different (y) ranges (different vertical scales).
Overlaid plots can also be obtained with the command plot(Y, x), where Y is an m × n matrix where x
can be either a row vector of length n or a column vector of length m. The command plot(X, Y), where
X and Y are two matrices with the same dimensions mxn. MATLAB returns a set of n plots, each one
representing the [columns of Y] versus [columns of X].
For example,
a. Let A = [1 2 3 4; 5 6 7 8; 9 10 11 12]. Write a program that returns the plots of each column of A
versus its index
b. Let B = [1 2 3]; obtain the plots of the columns of A versus the columns of B.
c. Now let B = [1 2 3 4]; obtain the plots of the rows of A versus the rows of B
MATLAB Solution

>> % part (a)

>> A= [1 2 3 4;5 6 7 8;9 10 11 12]

A =

1 2 3 4

5 6 7 8
9 10 11 12

>> plot (A)

>> title (‘Matrix A vs. Indexes’)

>> % part (b)

>> B = [1 2 3]

B =

1 2 3

>> plot (A,B)

>> % part (c)

>> B(4) = 4

B =

1 2 3 4

>> plot (A,B)

Subplots

The command subplot(m, n, p) returns m times n independent subwindows, where m and n indicate that the active fi
For example, subplot(2, 2, 3) indicates that the figure window is divided into four sub windows (two
rows by two columns) and the current plot sub window is the third (second row by first column).
For example, write a program that divides the window into four sub windows and plots in each one the
following functions:
−2 x
y 1=27 e ∧ y 2=15∗0.3 x over the range 1 x 5.
Represent the plot of y1 by discrete points indicated by the marker “*,” and y2 by a continuous (default)
solid line. Construct each plot using the following scales:
a. Linear (plot 1)
b. Linear-logarithmic (plot 2)
c. Logarithmic-linear (plot 3)
d. Logarithmic-logarithmic (plot 4)
MATLAB Solution

>> X = linspace(1,5,17);

>> y1 = 27*exp(-2*X);

>> y2 = 15*(0.3).^X;

>> % plot 1

>> subplot(2,2,1)

>> plot (X,y1,’*’,X,y2)

>> % plot 2

>> subplot(2,2,2)

>> semilogy(X,y1,’*’,X,y2)

>> % plot 3

>> subplot(2,2,3)

>> semilogx(X,y1,’*’,X,y2)

>> % plot 4

>> subplot(2,2,4)
>> loglog(X,y1,’*’,X,y2)

Labeling and Other Customizations


A good graph consists of properly labeled axis that includes units, a descriptive title, and any relevant
information about the plot.
The command grid on draws a set of grid lines superimposed on the active figure plot, whereas grid off
removes the grid lines. Grid lines can be very useful when estimating or viewing a plot. The command
box on places the plot inside a box. The command box off removes the box. It is common to label the x
and y axes of a plot with a descriptive text defining the variables used and its corresponding units such
as current in amperes, power in watts, frequency in hertz, or distance in meters.
The commands xlabel(‘text1’) and ylabel(‘text2’), where text1 and text2 are string vectors (in quotes)
are used to label, define, and describe the x- and y-axis and the associated variables. The command
title(‘text3’) places the string vector text3 at the top of the current plot as the figure title. The command
text(xa, ya, ’text4’) places the string vector text4 starting at the Cartesian coordinate location <x a, ya>
on the current figure window.
The command gtext(‘text5’) opens the current figure window, places a cursor making a cross hair, and
pauses. The center of the cross hair can be positioned anywhere on the active figure where the string
vector text5 can be placed by pressing the mouse button, or by pressing any key.
The string texts used in title, axis labels, and gtext may include about 100 special symbols including
Greek characters. Any Greek character (lower or capital) can be called by using the back slash (\)
character followed by its English version. Table below illustrates some of the most frequently used
characters and the corresponding syntax. Text superscripts can be created by using the character ^,
whereas text subscripts are created by the character _. Additional text control involving font style, font
size, marker size, and orientation are summarized below.

The command legend(‘text_1’, ‘text_2’, … ‘text_n’) is used to identify multiple plots on the same graph
by creating a box in the upper-right corner of the graph that returns the message text_1 on the first line,
identifying the line style used for the first plot; text_2 is placed on the second line and defines the line
type used for the second plot, …, and so on.
Problems

1)
let y1(x) = 10 sin(x) and y2(x) = 2 cos(x) + noise(x), where noise(x) is a random function over the range 0 x 3 u

a) [y1 = 10 sin(x)] versus x and [y2 = 2 cos(x) + noise(x)] versus. x using the same y scale
b) [y1 = 10 sin(x)] versus x and [y2 = 2 cos(x) + noise(x)] versus x using different y scales
2) Write a program that returns the following plots in a single figure:
a) [cos(x)] versus x and [sin(x)] versus x, representing the discrete points with the markers “*” and
“d,” respectively
b) [cos(x)] versus x and [sin(x)] versus x, showing the points defined by the markers in part a, and
by connecting the markers with a solid line.
Use 20 points linearly spaced over the range 0 x 2.
3) Generate an overlay plot for plotting three lines Use the plot command, the hold command and the
line command. Use the functions for plotting x-y data for plotting the following functions.
i ¿ f ( t ) =t cost , 0 ≤t ≤10 π
t 3t
ii ¿ x=e , y=100+ e ,0 ≤ t ≤ 2 π
4) Using appropriate example, make the following 2D plots

5) Create a program that returns the plots of y1(x) versus x and y2(x) versus x with the specs indicated
as follows:
a) Use the marker “*” to indicate the points of y1(x) and connect the points with a solid line
b) Use the marker “+” to indicate the points of y2(x) and connect the points with a solid line
c) Label properly the x and y axes
d) Place the following text as title: 5 cos(2X) and 3 sin(X) versus X
e) Place the text 5 cos 2x at the (Cartesian coordinate) location <0.5, 4>
f) Place the text 3 sin(X) using the command gtext at the (Cartesian coordinate) location <2, 3>
g) Add an appropriate legend onto your figure.
4 Lab 04
Object
To learn methods the flow of programming in MATLAB through loops.
4.1 Introduction
One most significant feature of MATLAB is its extendibility through user-written pro- grams such as
the M-files. M-files are ordinary ASCII text files written in MATLAB language. A function file is a
subprogram.
4.2 Relational and Logical Operators
A relational operator compares two numbers by finding whether a comparison statement is true or false.
A logical operator examines true/false statements and produces a result which is true or false according
to the specific operator. Relational and logical operators are used in mathematical expressions and also
in combination with other commands, to make decision that control the flow a computer program.
Table 3.1 MATLAB has six relational operators as shown below.

Examples showing relational commands for the case where the arguments, A and B are vectors, are
illustrated in Table below, for A=[0 12 3]∧B=[−1 2 13]
4.3 Order of Precedence
1 (highest) Parentheses (If nested parentheses exist, inner
have precedence).

2 Exponentiation.

3 Logical NOT (~).

4 Multiplication, Division.

5 Addition, Subtraction.

6 Relational operators (>, <, >=, <=, = =, ~=).

7 Logical AND (&).

8 (lowest) Logical OR (|).


4.4 Flow Control of a Program
The flow-control path of a program can be altered by each of the following four conditional MATLAB
commands:
a) the if-end
b) the for-end
c) the while-end
d) the switch-end
4.4.1 The If-End
A conditional statement is a command that allows MATLAB to make a decision of whether to execute a
group of commands that follow the conditional statement or to skip these commands.

The syntax and format of the simplest form of the if-end statement is as follows:
if <condition>

<statements>

end

Only one decision-making <condition> is used, and if this <condition> is true, then the <statements> are
executed, followed by the end. However, if the <condition> is false, then the <statements> are not
executed, followed by the end.
The if-end statement can be expanded to include two different paths by executing two different sets of
statements based on a single decision-making condition.
The syntax and format are as follows:
if <condition>

<statements _ 1>

else

<statements _ 2>

end

Meaning that if <condition> is true, then <statements_1> is executed followed by the end (exit); but if
<condition> is not true, then <statements_2> is executed followed by the end (exit). When several levels
of if-else statements are nested, it may be difficult to find which logical expressions must be true (or
false) to execute each set of statements. In such cases, the elseif clause is used to clarify the program
logic.
The syntax and format are as follows:
if <condition _ 1>

<statements _ 1>

elseif <condition _ 2>

<statements _ 2> and so on…

else

<statements _ n>

end

Meaning that if <condition_1> is true, then the <statements_1> are executed followed by the end (exit); but if <cond

4.4.2 The For-End


The command
for <range>

<statements>
end

referred as the for-end statement is used to create a loop that executes repetitively the <statements> a fix
number of times based on the spec <range>. The spec <range> is frequently given by a vector or a
matrix. In either case, the commands between the for and end indicated by <statements> are executed
once for each column of the <range>.
If multiple loops are required, the loop structure must be nested, meaning that each loop must be
constructed inside another loop.
The commands break, error, and return are useful when operating inside a loop to stop or
control its execution. The break command unconditionally terminates the execution of a loop and the
program continues with the first instruction after the end command. The command error (‘text’) stops
the execution of a loop, displays the string text on the computer screen, and transfers control to the
keyboard. The command return produces an unconditional exit from a loop, ignoring the instructions
inside the loop.
A few words of advice—a good programmer must be able to understand the mechanisms and conditions
set, and trace the logic used in repeating a block of commands by using loops and nested loops when
analyzing a program. Looping and decision making constitutes, the main power and capability of most
digital computer systems. The analysis of a looping sequence must be followed either mentally by the
experienced programmer or by relying on a flowchart or table by the beginner or less experienced
programmer. A recommended practice is to assign values to the loop variables tracing its execution for
at least two complete cycles to get a good insight of the mechanism used and be able to visualize a
pattern of the purpose and nature of the looping algorithm.
4.4.3 The While-End
The command
while <condition>

<statements>

end,

referred as the while-end statements is used to create a loop in which the <statements> are executed
repetitively for an indefinite number of times as long as the specified <condition> is and remains true.
When the <condition> is no longer true, then the program exits the loop and continues with the normal
execution of the remaining of the program by executing the first instruction after the end statement.
Lab Exercise 04
1) Write a program that returns
a) The matrix B with the information that indicates if each element of A is greater than 2
b) The matrix C with the information that indicates if each element of A is negative
c) The matrix D with the information that indicates if each element of A is equal to 2

2) Write a MATLAB program that returns


a) An array C with the information indicating if the elements in A are greater than the elements in B
b) An array D with the information indicating if the elements in A are equal to the corresponding
elements in B
c) An array E with the information indicating if the elements in A are smaller than the elements in
B
d) An array F with the information indicating if the elements in B are positive
e) An array G with the information indicating if the elements in A are greater or equal to 5
3)
For example, let A = 1:10 and B = (2).^A. Write and execute the MATLAB statements that return
a) An array C that indicates the locations where A > 6 and B < 3
b) An array D that indicates the locations where A > 6 or B < 3

4) In the given syntax below, write down the probable output or comment corresponding to each line.

Syntax Output

>> format compact.

>> A = [0 1 2; 4 5 6; -1 -2 -3]
>> X = -3:10

>> Y= []

>> String =’ABC’

>> all(X) % part (a)

>> all(A) % part (b)

>> all(Y) % part (c)

>> C = ones(1,14)./X % part (d)

>> any(X) % observe that one element

>> isnumeric(A) % part (e)

>> isempty(A) % part (f)

>> isempty(Y) % part (g)

>> isinf(A) % part (h)

>> isfinite(A) % part (i)

>> isinf(C) % part (j)

>> find(A) % part(k)

>> ischar(String) % part (l)


Problems
1) Display the use of decision structures by creating a script file plot_cos_spikes that returns the

plot of y (x )=10 cos( )


2 πx
100
where x runs from 1 to 100 and y(x) takes the following values at

the points defined by x=25 , 50 , 75 ,∧100 , y (25)=20 , y (50)=−30 , y (75)=20 ,∧ y (100)=−30.


2) Test the value for a given variable a and return one condition message indicating pass or fail.
The test conditions are
a. a > 80, the condition fails
b. a > 75, the condition fails
c. a > 70, the condition passes
d. a > 60, the condition fails
e. a > 50, the condition fails
Each fail must also contain a beep.
3) Create the script file check_age that returns one of the following messages: teenager, adult, and
senior given as the input of the variable age.
4) Write a program that returns the following sequence: C = [ 1 1/2 1/3 1/4 1/5 … 1/10] as a column
vector using for loop and while loop.
5) What would be the output of the following code:
% Script file: sum _ prod

disp(‘*****************************************’)

disp(‘ This script returns the sum and product ‘)

disp(‘of each column of the matrix A defined below’)

disp(‘******************************************’)

format compact

n =1;

A= [3 7 4;2 5 7;-1 -2 -3]

for K= A

fprintf (‘The sum and product of the elements of column %1.1f\n’,n)

ColumnSum = K(1)+K(2)+K(3)

ColumnProd = K(1)*K(2)*K(3)

n = n+1;

end
6) write a program that returns a 13 by 3 matrix A where the first column of A consists of the
sequence 1, 2, 3, 4, …, 13; the second column of A consists of the sequence 2, 4, 6, 8, …, 24, 26;
and the third column of A consists of the sequence 3, 6, 9, 12, …, 36, 39.

7) Create a script file explore that returns the plot of y = 5 √ ❑


over the range 1 k 5 in discrete increments of K
8) Will the following loop run infinitely? If yes, where should you use the break statement to
terminate the program on desired output.
n =1
x = 1
while x>0.5
y = 2.^x
x = x+0.1
n = n+1
if n=1000
disp(‘exit after 1000 iterations’)

end
end
9) Create a program that evaluates the sum_x defined by the following equation (for the first 10
digits) using a for and a while loop.
5 Lab 05
Object
To learn to use MATLAB to (1) generate polynomials, (2) manipulate polynomials, (3) perform partial-
fraction expansions. (4) find Laplace transforms for time functions and, (5) find time functions from
Inverse Laplace transforms
5.1 Control Systems Fundamentals
A basic control system has an input, a process, and an output. The basic objective of a control system is
of regulating the value of some physical variable or causing that variable to change in a prescribed
manner in time. Control systems are typically classified as open loop or closed-loop. Open-loop control
systems do not monitor or correct the output for disturbances whereas closed-loop control systems do
monitor the output and compare it with the input. In a closed-loop control system if an error is detected,
the system corrects the output and thereby corrects the effects of disturbances. In closed-loop control
systems, the system uses feedback, which is the process of measuring a control variable and returning
the output to influence the value of the variable.

Block diagrams display the operational units of a control system. Each block in a component block
diagram represents some major component of the control system, such as measurement, compensation,
error detection, and the plant itself. It also depicts the major directions of information and energy flow
from one component to another in a control system. A block can represent the component or process to
be controlled. Each block of a control system has a transfer function (represented by differential
equations) and defines the block output as a function of the input.
Control systems engineering consists of analysis and design of control systems configurations. Control
systems are dynamic, in that they respond to an input by first undergoing a transient response before
attaining a steady-state response which corresponds to the input.
There are three main objectives of control systems analysis and design. They are:
1. Producing the response to a transient disturbance which is acceptable
2. Minimizing the steady-state errors: Here, the concern is about the accuracy of the steady-state
response
3. Achieving stability: Control systems must be designed to be stable. Their natural response should
decay to a zero value as time approaches infinity, or oscillate.
System analysis means the investigation, under specified condition, of the performance of a system
whose mathematical model is known. Analysis is investigation of the properties and performance of an
existing control system.
By synthesis we mean using an explicit procedure to find a system that will perform in a specified way.
System design refers to the process of finding a system that accomplishes a given task. Design is the
selection and arrangement of the control system components to perform a prescribed task. The design of
control systems is accomplished in two ways: design by analysis in which the characteristics of an
existing or standard system configuration are modified, and design by synthesis, in which the form of
the control system is obtained directly from its specifications.
Control system design and analysis objectives include: producing the response to a transient disturbance
follows a specified pattern (over-damped or under damped), minimizing the steady-state errors, and
achieving the stability.
5.2 Polynomials in MATLAB
A polynomial is a function of a single variable that can be expressed in the following form:
f (x)=a0 x n+ a1 x n – 1 +a2 x n – 2 +…+ an – 1 x 1 +a n

where the variable is x and the coefficients of the polynomial are represented by the values a0, a1, …
and so on. The degree of a polynomial is equal to the largest value used as an exponent.
A vector represents a polynomial in MATLAB. When entering the data in MATLAB, simply enter each
coefficient of the polynomial into the vector in descending order. For example, consider the polynomial
5 4 2
5 s +7 s +2 s – 6 s+10
To enter this into MATLAB , we enter this as a vector as
>> x = [5 7 0 2 – 6 10]

x =

5 7 0 2 – 6 10

It is necessary to enter the coefficients of all the terms. MATLAB contains functions that perform
polynomial multiplication and division, which are listed below:
conv(a, b) Computes a coefficient vector that contains the coefficients of the product of polynomials
represented by the coefficients in a and b. The vectors a and b do not have to be the same size.
[q, r] = deconv(n, d) Returns two vectors. The first vector contains the coefficients of the
quotient and the second vector contains the coefficients of the remainder polynomial.
The MATLAB function for determining the roots of a polynomial is the roots function:
root(a) Determines the roots of the polynomial represented by the coefficient vector a. The roots
function returns a column vector containing the roots of the polynomial; the number of roots is equal to
the degree of the polynomial.
poly(r) Determines the coefficients of the polynomial whose roots are contained in the vector r. The
output of the function is a row vector containing the polynomial coefficients. The value of a polynomial
can be computed using the polyval function, polyval (a, x). It evaluates a polynomial with
coefficients a for the values in x. The result is a matrix the same size ad x. For instance, to find the value
of the above polynomial at s = 2,
>> x = polyval([5 7 0 2 – 6 10], 2)

x =

278

To find the roots of the above polynomial, we enter the command roots (a) which determines the roots
of the polynomial represented by the coefficient vector a.
>>roots([5 7 0 2 – 6 10])

ans =

– 1.8652

– 0.4641 + 1.0832i

– 0.4641 – 1.0832i

0.6967 + 0.5355i

0.6967 – 0.5355i

% or

>> x = [5 7 0 2 – 6 10]

x =

5 7 0 2 – 6 10

>> r = roots(x)

r =

– 1.8652

– 0.4641 + 1.0832i

– 0.4641 – 1.0832i
0.6967 + 0.5355i

0.6967 – 0.5355i

>>poly(r)

1.0000 1.4000 0.0000 0.4000 -1.2000 2.0000

the command poly always returns a value of unity to the leading coefficient. To multiply two
polynomials together, we enter the command conv.

The polynomials are: x=2 x+ 5∧ y =x2 +3 x +7

>>x = [2 5];

>>y = [1 3 7];

>>z = conv(x, y)

z =

2 11 29 35

To divide two polynomials, we use the command deconv. The MATLAB command [D, R] =
P1 R
deconv (P1, P2) performs the following polynomial operation, =D+ , and returns D and R
P2 P2
as row vectors, where D is the quotient polynomial and R is the residue or remainder polynomial.
z = [2 11 29 35]; x = [2 5]

>> [g, t] = deconv (z, x)

g = 1 3 7

t = 0 0 0 0

5.3 Partial Fraction Expansion


The Laplace transformation method is an operational method that can be used to find the transforms of
time functions, the inverse Laplace transformation using the partial-fraction expansion of B(s)/A(s),
where A(s) and B(s) are polynomials in s. In this lab, we present the computational methods with
MATLAB to obtain the partial-fraction expansion of B(s)/A(s).
MATLAB can be used to obtain the partial-fraction expansion of the ratio of two polynomials, B(s)/A(s)
as follows:
where a(1) 0 and num and den are row vectors. The coefficients of the numerator and denominator of B(s)/A(s) are

Hence,
num = [b(1) b(2) … b(n)]

den = [a(1) a(2) … a(n)]

The MATLAB command


r, p, k = residue(num, den) is used to determine the residues, poles, and direct terms of a
partial-fraction expansion of the ratio of two polynomials B(s) and A(s) is then given by
Resolve the given fraction analytically into its partial fractions.

The MATLAB command [num, den] = residue (r, p, k), where r, p and, k are the output
from MATLAB converts the partial fraction expansion back to the polynomial ratio B(s)/A(s).
Example:
Resolve the given fraction into its constituent partial fractions.

So, for the current problem, resolve into partial fractions


numf=2; % This is the numerator

denf=poly([-1 -2 -2]); %This is the denominator

[K,p,k]= residue (numf,denf) %The residue function takes the num and den as

input arguments

MATLAB OUTPUT:
The K vector gives the values of the residues, the p vector returns the polynomial values (poles which
we will study later!) and the k vector returns any constant or extra terms in the partial fraction
expansion. (In this case there are none). Hence, the final output can be considered as:
2 -2 -2 2

------------ = -------- + -------- + -------- + 0

(s+1)(s+2)^2 (s + 1) (s + 2) (s + 2)^2

5.4 MATLAB Symbolic Toolbox


In this section some of MATLAB’s capabilities for symbolic manipulations will be presented.
Specifically, the symbolic expressions, symbolic algebra, simplification of mathematical expressions,
operations on symbolic expressions, solution of a single equation or a set of linear algebraic equations,
solutions to differential equations, differentiation and integration of functions using MATLAB are
presented. The MATLAB Symbolic Toolbox provides access to a number of specialized functions used
in engineering and technology.
5.4.1 Symbolic Expression
A symbolic expression is stored in MATLAB as a character string. A single quote marks are used to
define the symbolic expression. For instance:
‘sin(y/x)’ ; ‘x ^ 4 + 5*x^3 + 7*x^2 – 7’

The independent variable in many functions is specified as an additional function argument. If an


independent variable is not specified, then MATLAB will pick one. When several variables exist,
MATLAB will pick the one that is a single lower-case letter (except i and j), which is closest to x
alphabetically. The independent variable is returned by the function symvar.

symvar(s) Returns the independent variable for the symbolic expression s. symvar(S) searches the
string S for identifiers other than 'i', 'j’, ‘pi', 'inf', 'nan', 'eps' and common functions. The variables are
returned as a cell array of strings. If no such variable exists, the empty cell array {} is returned.
For example:

Expression s symvar(s)

‘5 * c * d + 34’ {‘c’}, {‘d’}


‘sin(y/x)’ {‘x’}, {‘y’}

In MATLAB, a number of functions are available to simplify mathematical expressions by expanding


the terms, factoring expressions, collecting coefficients, or simplifying the expression. For instance:
expand(s) Performs an expansion of s.
A summary of these expressions is given in Table below.

5.5 Introduction to Laplace/Inverse Laplace Transformation in MATLAB


The purpose of the Laplace Transform is to transform ordinary differential equations (ODEs) into
algebraic equations, which makes it easier to solve ODEs. A system represented by a differential
equation is difficult to model as a block diagram. Thus, by using the Laplace transform we can represent
the input, output, and system as separate entities and their interrelationship becomes simply algebraic.
The Laplace transformation method is an operational method that can be used to find the transforms of
time functions, the inverse Laplace transformation using the partial-fraction expansion of B(s)/A(s),
where A(s) and B(s) are polynomials in s.
In this lab, we present the computational methods with MATLAB to obtain Laplace transformation and
inverse Laplace transformation using the MATLAB symbolic toolbox.

Find the laplace transform of the function f ( t )=−7 t e−5 t

>>syms t >>syms t x

>>f = – 7*t*exp(– 5*t); >>f = – 7*t*exp(– 5*t);

>> laplace(f) >> laplace(f, x)

ans = ans =

– 7/(s + 5)^2 – 7/(x + 5)^2

The partial fractions obtained in the previous section were as follows:


2 -2 -2 2

------------ = -------- + -------- + -------- + 0

(s+1)(s+2)^2 (s + 1) (s + 2) (s + 2)^2

The command ilaplace will find the inverse Laplace transform of a Laplace function.

syms s %The syms function makes s a symbol that is treated like a variable

f=ilaplace(3/(s*(s^2+2 *s+5))); %write down entire fraction

Output:

f =

2*exp(-t) - 2*exp(-2*t) - 2*t*exp(-2*t)

Use the pretty command to give your output a standard look similar to textbook mathematical
expressions.
pretty(f) %makes the output easier to read

Output:

2exp(-t) - exp(-2t) 2 – t exp(-2t) 2


Lab Exercise 05

1) Evaluate the given polynomial at x = 0; p( x )=π x 4 – √ ❑ using MATLAB.

2) Evaluate the following polynomials using MATLAB


3) Find the partial fraction expansion for the following fraction expressed as factors in the numerator
divided by factors in the denominator using MATLAB
8 ( s +1 )( s+3 )
a) G1 ( s )=
( s +2 ) ( s+ 4 )( s+6 )2

b)

4) Expand the following function F(s) into partial fractions using MATLAB. Determine the inverse
Laplace transform of F(s).
5) Find the Laplace transform of the following function using MATLAB.
a) f (t )=7 t 3 cos(5 t +60 °)
b) f (t)=5 e – 2 t cos 5 t

6) Use MATLAB and the Symbolic Math Toolbox to


a) Generate symbolically the time function f(t) shown.

b) Generate symbolically F(s) shown. Obtain your result symbolically in both factored and
polynomial forms.
c) Find the Laplace transform of f(t) shown in part a.
d) Find the inverse Laplace transform of F(s) shown in part b
6 Lab 06
Object
To learn to use MATLAB to (1) generate transfer functions, (2) manipulate transfer functions, (3)
identifying poles and zeros of transfer functions (4) plotting poles and zeros of transfer functions (5) To
study model conversion techniques
6.1 Transfer Functions
The transfer function of a linear time invariant system is expressed as a ratio of two polynomials. The
transfer function for a single input and a single output (SISO) system is written as:

You can use the tf command to generate a transfer function directly as well. Like the residue command
it takes the coefficients of numerator and the denominator as input vectors.
F=tf([3],[1 2 5 0])

Output:

A useful trick is to create the Laplace variable, s. That way, you can specify polynomials using s as the
polynomial variable and easily represent the same transfer function.

>>s=tf('s');
>>sys= s/(s^2 + 2*s + 1)
The command printsys (num, den, ‘s’) prints the numerator and the denominator in terms of
the ratio of polynomials in terms of the transform variable s. It is described the example below.
Consider the transfer functions
2
6 s +1
G ( s )= 3 2
∧ H ( s )=¿ ¿
s +3 s + 3 s+ 1
numg = [6 0 1]; deng = [1 3 3 1];

printsys(numg, deng)

MATLAB Code %Add a Comment

Write a code for H(s)

Final Output for H(s)

Write a code to evaluate G(s)/H(s) and then print the entire system

Final output for G(s)/H(s)

6.2 Poles and Zeros


After the engineer obtains a mathematical representation of a subsystem, the subsystem is analyzed for
its transient and steady-state responses to see if these characteristics yield the desired behavior. This lab
is devoted to the analysis of system transient response.
The concept of poles and zeros, fundamental to the analysis and design of control systems, simplifies the
evaluation of a system’s response. The poles of a transfer function are (1) the values of the Laplace
transform variable, s, that cause the transfer function to become infinite or (2) any roots of the
denominator of the transfer function that are common to roots of the numerator whereas the zeros of a
transfer function are (1) the values of the Laplace transform variable, s, that cause the transfer function
to become zero, or (2) any roots of the numerator of the transfer function that are common to roots of the
denominator.
Given the transfer function G(s) in Figure (a), a pole exists at s=-5, and a zero exists at -2. These values
are plotted on the complex s-plane, using an × for the pole and a O for the zero.
s +2
G ( s )=
s +5
Use the following MATLAB and Control System Toolbox statement to form the linear, time-invariant
(LTI) transfer function of the following transfer function:
F=zpk([], [-1 -2 -2],2)

It will give you the following output:

The MATLAB command [z, p, k] = tf2zp(num,den) is used to find the zeros, poles, and gain K
of B(s)/A(s).If the zeros, poles, and gain K are given, the following MATLAB command can be used to
find the original num/den: [num,den] = zp2tf (z, p, k)

The pole zero’s locations can also me displayed as a map on the complex plane using the pzmap
command. pzmap(num,den)
5 4 3 2
6 s +18 s +25 s +75 s +4 s +12
G ( s )= 5 4 3 2
s +6 s +14 s + 16 s + 9 s +2
The pole-zero map clearly shows the five zero locations and two pole locations. This cannot be the case
since we know that the number of poles must be greater than or equal to the number of zeros. Using the
roots function, we can be certain that there are in fact four poles at s = -1. Hence, multiple poles or
multiple zeros at the same location cannot be discerned on the pole-zero map.
6.3 Model Conversion
There are a number of functions in MATLAB that can be used to convert from one model to another.
These conversion functions and their applications are summarized in Table below:

State Space Models


hh For continuous linear time-invariant (LTI) systems, the standard state-space representation is given
below:
where is the vector of state variables (nx1), is the time derivative of the state vector (nx1), is the
input or control vector (px1), is the output vector (qx1), is the system matrix (nxn), is the input
matrix (nxp), is the output matrix (qxn), and is the feedforward matrix (qxp).
The output equation y, is necessary because often there are state variables which are not directly
observed or are otherwise not of interest. The output matrix, , is used to specify which state variables
(or combinations thereof) are available for use by the controller. Also, it is often the case that the outputs
do not directly depend on the inputs (only through the state variables), in which case is the zero
matrix.
The state-space representation, also referred to as the time-domain representation, can easily
handle multi-input/multi-output (MIMO) systems, systems with non-zero initial conditions, and
nonlinear systems via Equation (1). Consequently, the state-space representation is used extensively in
"modern" control theory.
ss2tf Function: The ss2tf function converts the continuous-time, state-space equations
x '= Ax+ Bu
y=Cx + Du
to the polynomial transfer function

The function has two output matrices:


[num, den] = ss2tf(A, B, C, D, iu) Computes vectors num and den containing the
coefficients, in descending powers of s, of the numerator and denominator of the polynomial transfer
function for the iuth input. The input arguments A, B, C, and D are the matrices of the state-space
equations corresponding to the iuth input, where iu is the number of the input for a multi-input system.
In the case of a single-input system, iu is 1.
ss2zp Function: The ss2zp function converts the continuous-time, state-space equations
x '= Ax+ Bu
y=Cx + Du
to the zero-pole-gain transfer function
The function has three output matrices:
[z, p, k] = ss2zp(A, B, C, D, iu) Determines the zeros (z) and poles (p) of the zero-pole
gain transfer function for the iuth input, along with the associated gain (k). The input matrices A, B, C,
and D of the state-space equations correspond to the iuth input, where iu is the number of the input for a
multi-input system. In the case of a single-input system iu is 1.
tf2ss Function: The tf 2ss function converts the polynomial transfer function

to the controller-canonical form state-space equations


x '= Ax+ Bu
y=Cx + Du
The function has four output matrices:
[A,B,C,D] = tf2ss(num,den) Determines the matrices A, B, C, and D of the controller canonical
form state-space equations. The input arguments num and den contain the coefficients, in descending
powers of s, of the numerator and denominator polynomials of the transfer function that is to be
converted.
tf2zp Function: The tf2zp function converts the polynomial transfer function

to the zero-pole-gain transfer function

The function has three output matrices:


[z, p, k] = tf2zp(num,den) Determines the zeros (z), poles (p) and associated gain (k) of the
zero-pole-gain transfer function using the coefficients, in descending powers of s, of the numerator and
denominator of the polynomial transfer function that is to be converted.
zp2tf Function: The zp2tf function converts the zero-pole-gain transfer function

to the polynomial transfer function


The function has two output matrices:
[num, den] = zp2tf(z, p, k) Determines the vectors num and den containing the coefficients, in
descending powers of s, of the numerator and denominator of the polynomial transfer function. p is a
column vector of the pole locations of the zero-pole-gain transfer function, z is a matrix of the
corresponding zero locations, having one column for each output of a multi-output system, k is the gain
of the zero-pole-gain transfer function. In the case of a single-output system, z is a column vector of the
zero locations corresponding to the pole locations of vector p.
zp2ss Function: The zp2ss function converts the zero-pole-gain transfer function

to the controller-canonical form state-space equations


x '= Ax+ Bu
y=Cx + Du
The function has four output matrices:
[A, B, C, D] = zp2ss(z, p, k) Determines the matrices A, B, C, and D of the control canonical
form state-space equations. p is a column vector of the pole locations of the zero-pole gain transfer
function, z is a matrix of the corresponding zero locations, having one column for each output of a
multi-output system, k is the gain of the zero-pole-gain transfer function. In the case of a single-output
system, z is a column vector of the zero locations corresponding to the pole locations of vector p.
Mechanical Systems
Newton's laws of motion form the basis for analyzing mechanical systems. Newton’s second law, states
that the sum of the forces acting on a body equals the product of its mass and acceleration. Newton's
third law, for our purposes, states that if two bodies are in contact, then they experience the same
magnitude contact force, just acting in opposite directions.

When applying this equation, it is best to construct a free-body diagram (FBD) of the system showing all
of the applied forces.
Example: Mass-Spring-Damper System
The free-body diagram for this system is shown below. The spring force is proportional to the
displacement of the mass, , and the viscous damping force is proportional to the velocity of the
mass, . Both forces oppose the motion of the mass and are, therefore, shown in the negative -
direction. Note also that corresponds to the position of the mass when the spring is unstretched.

Now we proceed by summing the forces and applying Newton’s second law, Equation (11), in each
direction. In this case, there are no forces acting in the -direction; however, in the -direction we have:

This equation, known as the governing equation, completely characterizes the dynamic state of the
system. Later, we will see how to use this to calculate the response of the system to any external
input, , as well as to analyze system properties such as stability and performance.
To determine the state-space representation of the mass-spring-damper system, we must reduce the
second-order governing equation to a set of two first-order differential equations. To this end, we choose
the position and velocity as our state variables.

The position variable captures the potential energy stored in the spring, while the velocity variable
captures the kinetic energy stored by the mass. The damper only dissipates energy, it doesn't store
energy. Often when choosing state variables it is helpful to consider what variables capture the energy
stored in the system.
The state equation in this case is:
If, for instance, we are interested in controlling the position of the mass, then the output equation is:

Entering State-Space Models into MATLAB


Now we will demonstrate how to enter the equations derived above into an m-file for MATLAB. Let's
assign the following numerical values to each of the variables.
m mass 1.0 kg
k spring constant 1.0 N/m
b damping constant 0.2 Ns/m
F input force 1.0 N
Create a new m-file and enter the following commands.
m = 1;
k = 1;
b = 0.2;
F = 1;

A = [0 1; -k/m -b/m];
B = [0 1/m]';
C = [1 0];
D = [0];

sys = ss(A,B,C,D)
sys =

A =
x1 x2
x1 0 1
x2 -1 -0.2
B =
u1
x1 0
x2 1

C =
x1 x2
y1 1 0

D =
u1
y1 0

Continuous-time state-space model.


The Laplace transform for this system assuming zero initial conditions is

and, therefore, the transfer function from force input to displacement output is
Lab Exercise 06
1) Use MATLAB to find the zeros and poles of the given transfer function

2) Generate the following transfer functions using MATLAB

a) As the ratio of factors


b) As the ratio pf polynomials
7 Lab 07
Object
To learn the modeling of physical systems using Simulink
7.1 Overview
This lab introduces powerful graphical user interface (GUI), Simulink of Matlab. This software is used
for solving the modeling equations and obtaining the response of a system to different inputs. Both
linear and nonlinear differential equations can be solved numerically with high precision and speed,
allowing system responses to be calculated and displayed for many input functions. To provide an
interface between a system’s modeling equations and the digital computer, block diagrams drawn from
the system’s differential equations are used. A block diagram is an interconnection of blocks
representing basic mathematical operations in such a way that the overall diagram is equivalent to the
system’s mathematical model. The lines interconnecting the blocks represent the variables describing
the system behavior. These may be inputs, outputs, state variables, or other related variables. The blocks
represent operations or functions that use one or more of these variables to calculate other variables.
Block diagrams can represent modeling equations in both input-output and state variable form.
We use MATLAB with its companion package Simulink, which provides a graphical user interface
(GUI) for building system models and executing the simulation. These models are constructed by
drawing block diagrams representing the algebraic and differential equations that describe the system
behavior. The operations that we generally use in block diagrams are summation, gain, and integration.
Other blocks, including nonlinear elements such as multiplication, square root, exponential, logarithmic,
and other functions, are available.
Provisions are also included for supplying input functions, using a signal generator block, constants etc.
and for displaying results, using a scope block. An important feature of a numerical simulation is the
ease with which parameters can be varied and the results observed directly. MATLAB is used in a
supporting role to initialize parameter values and to produce plots of the system response. Also,
MATLAB is used for multiple runs for varying system parameters. Only a small subset of the functions
of MATLAB will be considered during these labs.
7.2 SIMULINK
Simulink provides access to an extensive set of blocks that accomplish a wide range of functions useful
for the simulation and analysis of dynamic systems. The blocks are grouped into libraries, by general
classes of functions.

Mathematical functions such as summers and gains are in the Math library.

Integrators are in the Continuous library.

Constants, common input functions, and clock can all be found in the Sources library.
Scope, To Workspace blocks can be found in the Sinks library.
Simulink is a graphical interface that allows the user to create programs that are actually run in
MATLAB. When these programs run, they create arrays of the variables defined in Simulink that can be
made available to MATLAB for analysis and/or plotting. The variables to be used in MATLAB must be
identified by Simulink using a “To Workspace” block, which is found in the Sinks library. (When using
this block, open its dialog box and specify that the save format should be Matrix, rather than the default,
which is called Structure.) The Sinks library also contains a Scope, which allows variables to be
displayed as the simulated system responds to an input. This is most useful when studying responses to
repetitive inputs. Simulink uses blocks to write a program. Blocks are arranged in various libraries
according to their functions. Properties of the blocks and the values can be changed in the associated
dialog boxes. Some of the blocks are given below.
7.2.1 SUM (Math library)
A dialog box obtained by double-clicking on the SUM block performs the configuration of the SUM
block, allowing any number of inputs and the sign of each. The sum block can be represented in two
ways in Simulink, by a circle or by a rectangle. Both choices are shown X1

Figure 1: Two Simulink blocks for a summer representing y = x 1+ x2 – x3


7.2.2 GAIN (Math library)
A gain block is shown by a triangular symbol, with the gain expression written inside if it will fit. If not,
the symbol - k - is used. The value used in each gain block is established in a dialog box that appears if
the user double-clicks on its block.

Figure 2: Simulink block for a gain of K.


7.2.3 INTEGRATOR (Continuous library)
The block for an integrator as shown below looks unusual. The quantity 1/s comes from the Laplace
transform expression for integration. When double-clicked on the symbol for an integrator, a dialog box
appears allowing the initial condition for that integrator to be specified. It may be implicit, and not
shown on the block, as in Figure (a). Alternatively, a second input to the block can be displayed to
supply the initial condition explicitly, as in part (b) of Figure 3. Initial conditions may be specific
numerical values, literal variables, or algebraic expressions.

Figure3: Two forms of the Simulink block for an integrator.


(a) Implicit initial condition. (b) Explicit initial condition.
7.2.4 CONSTANTS (Source library)
Constants are created by the Constant block, which closely resembles Figure 4. Double clicking on the
symbol opens a dialog box to establish the constant’s value. It can be a number or an algebraic
expression using constants whose values are defined in the workspace and are therefore known to
MATLAB.

Figure 4: A constant block


7.2.5 STEP (Source library)
A Simulink block is provided for a Step input, a signal that changes (usually from zero) to a specified
new, constant level at a specified time. These levels and time can be specified through the dialog box,
obtained by double-clicking on the Step block.

Figure 5: A step block


7.2.6 SIGNAL GENERATOR (Source library)
One source of repetitive signals in Simulink is called the Signal Generator. Double-clicking on the
Signal Generator block opens a dialog box, where a sine wave, a square wave, a ramp (sawtooth), or a
random waveform can be chosen. In addition, the amplitude and frequency of the signal may be
specified. The signals produced have a mean value of zero. The repetition frequency can be given in
Hertz (Hz), which is the same as cycles per second, or in radians/second.

Figure 6: A signal generator block


7.2.7 SCOPE (Sink library)
The system response can be examined graphically, as the simulation runs, using the Scope block in the
sinks library. This name is derived from the electronic instrument, oscilloscope, which performs a
similar function with electronic signals. Any of the variables in a Simulink diagram can be connected to
the Scope block, and when the simulation is started, that variable is displayed. It is possible to include
several Scope blocks. Also, it is possible to display several signals in the same scope block using a
MTJX block in the signals & systems library. The Scope normally chooses its scales automatically to
best display the data.

Figure 7: A scope block with MUX block


Two additional blocks will be needed if we wish to use MATLAB to plot the responses versus time.
These are the Clock and the To Workspace blocks.
7.2.8 CLOCK (Source library)
The clock produces the variable “time” that is associated with the integrators as MATLAB calculates a
numerical (digital) solution to a model of a continuous system. The result is a string of sample values of
each of the output variables. These samples are not necessarily at uniform time increments, so it is
necessary to have the variable “time” that contains the time corresponding to each sample point. Then
MATLAB can make plots versus “time.” The clock output could be given any arbitrary name; we use
“t” in most of the cases.

Figure 8: A clock block


7.2.9 To Workspace (Sink library)
The To Workspace block is used to return the results of a simulation to the MATLAB workspace, where
they can be analyzed and/or plotted. Any variable in a Simulink diagram can be connected to a “To
Workspace” block. In our exercises, all of the state variables and the input variables are usually returned
to the workspace. In addition, the result of any output equation that may be simulated would usually be
sent to the workspace. In the block parameters drop down window, change the save format to ‘array’.

Figure 9: A to Workspace block


In the Simulink diagram, the appearance of a block can be changed by changing the foreground or
background colors, or by drop shadow or other options available in the format drop down menu. The
available options can be reached in the Simulink window by highlighting the block, then clicking the
right mouse button. The Show Drop Shadow option is on the format drop-down menu. Simulink
provides scores of other blocks with different functions. You are encouraged to browse the Simulink
libraries and consult the online Help facility provided with MATLAB.
7.3 General Instructions for Writing a Simulink Program
To create a simulation in Simulink, follow the steps:

● Start MATLAB.

● Start Simulink.

● Open the libraries that contain the blocks you will need. These usually will include the Sources,
Sinks, Math and Continuous libraries, and possibly others.
● Open a new Simulink window.

● Drag the needed blocks from their library folders to that window. The Math library, for example,
contains the Gain and Sum blocks.
● Arrange these blocks in an orderly way corresponding to the equations to be solved.

● Interconnect the blocks by dragging the cursor from the output of one block to the input of another
block. Interconnecting branches can be made by right-clicking on an existing branch.
● Double-click on any block having parameters that must be established, and set these parameters. For
example, the gain of all Gain blocks must be set. The number and signs of the inputs to a Sum block
must be established. The parameters of any source blocks should also be set in this way.
● It is necessary to specify a stop time for the solution. This is done by clicking on the Simulation >
Parameter’s entry on the Simulink toolbar.
At the Simulation > Parameter’s entry, several parameters can be selected in this dialog box, but the
default values of all of them should be adequate for almost all of the exercises. If the response before
time zero is needed, it can be obtained by setting the Start time to a negative value. It may be necessary
in some problems to reduce the maximum integration step size used by the numerical algorithm. If the
plots of the results of a simulation appear “choppy” or composed of straight-line segments when they
should be smooth, reducing the max step size permitted can solve this problem.
7.4 Mass-Spring System Model
Consider the Mass-Spring system used in the previous exercise as shown in the figure, where F s (x) is
the spring force, F f (ν ) is the friction coefficient, x (t) is the displacement and F a (t) is the applied force

The differential equation for the above Mass-Spring system can then be written as follows

For Non-linear such case, (1) becomes

Exercise 1: Modeling of a second order system Construct a Simulink diagram to calculate the
response of the Mass-Spring system. The input force increases from 0 to 8 N at t = 1 s. The
parameter values are M = 2 kg, K= 16 N/m, and B =4 N.s/m. Steps:
Draw the free body diagram.
Write the modeling equation from the free body diagram
Solve the equations for the highest derivative of the output.
Draw a block diagram to represent this equation.
Draw the corresponding Simulink diagram.
Use Step block to provide the input fa(t).

In the Step block, set the initial and final values and the time at which the step occurs.

Use the “To Workspace” blocks for t, fa(t), x, and v in order to allow MATLAB to plot the desired responses. Set th

Select the duration of the simulation to be 10 seconds from the Simulation > Parameters entry on the toolbar.

Given below is a file that will set up the MATLAB workspace by establishing the values of
the parameters needed for the Simulink simulation of the given model. M-file for parameter values

M-file for parameter values


% This file is named exl_parameter.m.
% Everything after a % sign on a line is a comment that
% is ignored by M This file establishes the
% parameter values for exl_model.mdl.
M2; %kg
K= 16; %N/m
B=4; % Ns/m
Plotting the outputs in MATLAB:
The file to create the plots of the output is given below. Create the file and save it by the name given
below.
M-file to produce the plot
% This file is named exl_plot.m.
% It makes a plot of the data produced by exl_model.mdl.
plot(t, x); grid % Plots x for the case with B=4.
xlabel(’Time (s)’);
ylabel (‘Displacement (m) ')
A semicolon in a physical line ends the logical line, and anything after it is treated as if it
were on a new physical line. A semicolon at the end of a line that generates output to the
command window suppresses the printing of that output.
Program Execution:
Follow the following steps to execute these files:

● Enter the command exl_parameter in the command window. This will load the
parameter values of the model.
● Open the Simulink model exl_model.mdl and start the simulation by clicking on the toolbar entry
Simulation> Start.
● Enter the command exl_plot in the command window to make the plot.

Making Subplots in MATLAB:


When two or more variables are being studied simultaneously, it is frequently desirable to plot them one
above the other on separate axes, as can be done for displacement and velocity in. This is accomplished
with the subplot command. The following M-file uses this command to produce both plots of
displacement and velocity.
M-file to make subplots
% This file is named exl_plot2.m.
% It makes both plots, displacement and velocity.
% Execute exl_parameter.m first.
subplot(2,l,1);
plot(t,x); grid % Plots x for the case with B=4. xlabel (‘Time (s) ‘) ;
ylabel (‘Displacement (m) ‘); subplot(2,1,2);
plot(t,v); grid % Plots v for the case with B=4. xlabel(’Time (s)’);
ylabel(’Velocity (m per s)’);
Paste your plots over here once you are done with the exercise.

8 Lab 08
Object:
Learning simulation of linear systems with Unit Step and Impulse Inputs.
Theory:
Model is a mathematical representation of a system
– Models allow simulating the system
– Models can be used for conceptual analysis
– Models are never exact.
– Linear models
o Have simple structure.
o Can be analyzed using powerful mathematical tools.
o Can be matched against real data using known procedures.
o Many simple physics models are linear.
o They are just models, not the real systems.
You can simulate the LTI systems to inputs like impulse, step and other standard inputs and see the plot
of the response in the figure window. MATLAB command ‘impulse’ calculates the unit impulse
response of the system, ‘step’ calculates the unit step response of the system and ‘lsim’ simulates the
(time) response of continuous or discrete linear systems to arbitrary inputs. When invoked without left-
hand arguments, all three commands plots the response on the screen. For example:

The lsim command is quite similar to the step command (actually, the step command is just a special
case of lsim). Given a system described as an LTI object, the lsim command can run a simulation of the
system using arbitrary inputs and initial conditions.

The command lsim(sys,U,T,X0) plots the time response of a linear time-invariant system. This
system can be continuous or discrete. For a continuous-time system, the differential equation is
integrated from time T(0) to T(length(T)), starting at the initial condition X0 and using the input U. The
input vector must have the same number of entries as the time vector. If the initial conditions are all
zero, X0 may be omitted.

For a discrete-time system, U should be sampled at the same rate as the system (T is then redundant and
may be omitted or set to the empty matrix, i.e. [ ]).

Suppose we have a continuous-time system described by the following A, B, C, and D matrices.

A = [-20 -40 -60

1 0 0

0 1 0];

B = [1

0];

C = [0 0 1];

D = 0;

As you can see from the dimensions of the matrices, this system has three states, one input, and one
output. Let's say we want to plot the response of the system with a non-zero initial condition and no
input. This can be done in the following manner.

T = 0:0.01:10; % simulation time = 10 seconds


U = zeros(size(T)); % no input
X0 = [0.1 0.1 0.1]; % initial conditions of the three states
sys = ss(A,B,C,D); % construct a system model
lsim(sys, U, T, X0) % simulate and plot the response (the output)
title('Response to Non-Zero Initial Conditions')

When the lsim command is invoked with left-hand arguments,

[Y, Tsim, X] = lsim(sys,U,T);

no plot is drawn on the screen. MATLAB returns the output and state time history in the
matrices Y and X respectively. In general, Tsim is the same as T. However, in some cases, T is
resampled when intersample oscillations occur. Then, Tsim is the time actually used in simulation. The
matrix Y has as many columns as there are outputs and has length(Tsim) rows. X has as many columns
as there are states and has length(Tsim) rows. The plot command can then be used to plot the response.
Note that X can be omitted.
Now let's plot the step response for the system given above; the input U is 1 for all positive time, and let
the initial conditions be zero.

T = 0:0.01:10; % simulation time = 10 seconds


U = ones(size(T)); % u = 1, a step input
sys = ss(A,B,C,D); % construct a system model
[Y, Tsim, X] = lsim(sys,U,T); % simulate
plot(Tsim,Y) % plot the output vs. time
title('Step Response with Zero Initial Conditions')

The plot above shows the step response of the system. We can also plot the response of the system to
any other input that we choose. For example, we can simulate the system's response to a sinusoidal
input, say u(t) = 0.1 sin(5 t + 1), employing the code given below.

T = 0:0.01:10; % simulation time = 10 seconds


U = 0.1*sin(5*T+1); % input as a function of time
sys = ss(A,B,C,D); % construct a system model
[Y, Tsim, X] = lsim(sys,U,T); % simulate
plot(Tsim,Y) % plot the output vs. time
title('Response to a Sinusoid Input with Zero Initial Conditions')
Remember that the steady-state response of a linear system to a sinusoidal input will always be a
sinusoid of the same frequency but with a different magnitude and phase. The response shown above is
consistent with this fact.
The lsim command also works with other LTI objects, such as in transfer function form (continuous or
discrete). Running the following code will generate the same response found above.

T = 0:0.01:10;

U = 0.1*sin(5*T+1);

num=1;

den=[1 20 40 60];

sys_tf = tf(num,den);

lsim(sys_tf,U,T);

Because any transfer function can be represented using many different sets of state-space matrices, you
can only simulate a system in transfer function form with zero initial conditions (and cannot obtain the
state trajectories); see the conversions page for more details.
The response of linear systems to arbitrary inputs can also be generated from within the Linear System
Analyzer.
Practice:
To obtain an impulse response
>> H = tf([2 5 1],[1 2 3]);

>>impulse(H)

To obtain a step response type


>>step(H)

Time-interval specification:
To contain the response of the system you can also specify the time interval to simulate the system to.
For example,
>> t = 0:0.01:10;
>> impulse(H,t)
Or
>> step(H,t)
Simulation to Arbitrary Inputs:
To simulates the (time) response of continuous or discrete linear systems to arbitrary inputs use ‘lsim’.
When invoked without left-hand arguments, ‘lsim’ plots the response on the screen. lsim(sys,u,t)
produces a plot of the time response of the LTI model sys to the input time history ‘t’,’u’. The vector ‘t’
specifies the time samples for the simulation and consists of regularly spaced time samples.
T = 0:dt:Tfinal
The matrix u must have as many rows as time samples (length(t)) and as many columns as system
inputs.

Simulate and plot the response of the system:

to a square wave with period of four seconds.


First generate the square wave with gensig. Sample every 0.1 second during 10 seconds:
>>[u,t] = gensig(‘square’,4,10,0.1);
Then simulate with lsim.
>> H = tf([2 5 1],[1 2 3])
>> lsim(H,u,t)
Paste your output here.
Lab Exercise 08
9 Lab 09
Object
Open Ended Lab:
Continued with the learning of Mathematical Modeling from previous experiment, perform modeling
analysis of an electrical, mechanical or rotational system of your choice using the control system toolbox
in MATLAB and Simulink.
List of Equipment/Software
Following equipment/software is required:

⮚ MATLAB

⮚ Simulink

Category
Soft-Experiment
Deliverables
A complete lab report including the following:

⮚ Theory of electrical network systems, translational and rotational mechanical systems.

⮚ Design two systems in Simulink, one for impulse response and one for step response. Then use the
derived transfer function to obtain the result using scope. To find both the responses in MATLAB,
write the required code and finally compare both the results (of Simulink and MATLAB).
⮚ MATLAB scripts and their results for all the assignments and exercises should be properly reported.
10 Lab 10
Object
To learn commands in MATLAB that would be used to reduce linear systems block diagram using
series, parallel and feedback configuration.

Series configuration: If the two blocks are connected as shown below then the blocks are said to
be in series. It would like multiplying two transfer functions. The MATLAB command for the
such configuration is “series”.

The series command is implemented as shown below:

Example 1: Given the transfer functions of individual blocks generate the system transfer
function of the block combinations.

The result is as shown below:

Parallel configuration: If the two blocks are connected as shown below then the blocks are said to be in
parallel. It would like adding two transfer functions.
The MATLAB command for implementing a parallel configuration is “parallel” as shown
below:

Example 2: For the previous systems defined, modify the MATLAB commands to obtain the
overall transfer function when the two blocks are in parallel.

Feedback configuration: If the blocks are connected as shown below then the blocks are said to
be in feedback. Notice that in the feedback there is no transfer function H(s) defined. When not
specified, H(s) is unity. Such a system is said to be a unity feedback system.

The MATLAB command for implementing a feedback system is “feedback” as shown below:

When H(s) is non-unity or specified, such a system is said to be a non-unity feedback system as
shown below:
A non-unity feedback system is implemented in MATLAB using the same “feedback”
command as shown:

Example 3: Given a unity feedback system as shown in the figure, obtain the overall transfer
function using MATLAB:

The result is as shown below:

Example 4: Given a non-unity feedback system as shown in the figure, obtain the overall
transfer function using MATLAB:
The result is as shown below:

Exercise 1: For the following multi-loop feedback system, get closed loop transfer function and the
corresponding pole-zero map of the system.
Lab Exercise 10
11 Lab 11
Object
to study the performance characteristics of first order systems using MATLAB
Overview First Order Systems:
An electrical RC-circuit is the simplest example of a first order system. It comprises of a resistor and
capacitor connected in series to a voltage supply as shown below on Figure 1.

If the capacitor is initially uncharged at zero voltage when the circuit is switched on, it starts to charge
due to the current ‘i' through the resistor until the voltage across it reaches the supply voltage. As soon
as this happens, the current stops flowing or decays to zero, and the circuit becomes like an open circuit.
However, if the supply voltage is removed, and the circuit is closed, the capacitor will discharge the
energy it stored again through the resistor. The time it takes the capacitor to charge depends on the time
constant of the system, which is defined as the time taken by the voltage across the capacitor to rise to
approximately 63% of the supply voltage. For a given RC-circuit, this time constant is r = RC. Hence its
magnitude depends on the values of the circuit components.
The RC circuit will always behave in this way, no matter what the values of the components. That is, the
voltage across the capacitor will never increase indefinitely. In this respect we will say that the system is
passive and because of this property it is stable.
For the RC-circuit as shown in Fig. 1, the equation governing its behavior is given by

where vc(t) is the voltage across the capacitor, R is the resistance and C is the capacitance. The constant
τ = RC is the time constant of the system and is defined as the time required by the system output i.e.
v c (t) to rise to 63% of its final value (which is E). Hence the above equation can be expressed in terms
of the time constant as:
Obtaining the transfer function of the above differential equation, we get

where τ is time constant of the system and the system is known as the first order system. The
performance measures of a first order system are its time constant and its steady state.
Exercise
a) Given the values of R and C, obtain the unit step response of the first order system.
a. R=2KΩ and C=0.01F
b. R=2.5KΩ and C=0.003F
b) Verify in each case that the calculated time constant (r = RC) and the one measured from the
figure as 63% of the final value are same. Obtain the steady state value of the system
12 Lab 12
Object

Overview of Second Order Systems


Consider the following Mass-Spring system shown in the Figure 2. Where K is the spring constant, B is
the friction coefficient, x(t) is the displacement and F(t) is the applied force:

The differential equation for the above Mass-Spring system can be derived as follows.

Applying the Laplace transformation, we get

provided that, all the initial conditions are zeros. Then the transfer function representation of the system
is given by

The above system is known as a second order system.


The generalized notation for a second order system described above can be written as

With the step input applied to the system, we obtain


for which the transient output, as obtained from the Laplace transform, is

where 0 < ζ < 1. The transient response of the system changes for different values of damping ratio, ζ.
Standard performance measures for a second order feedback system are defined in terms of step
response of a system. Where, the response of the second order system is shown below.

The performance measures could be described as follows:


Rise Time: The time for a system to respond to a step input and attains a response equal to a percentage
of the magnitude of the input. The 0-100% rise time, Tr, measures the time to 100% of the magnitude of
the input. Alternatively, Tr1, measures the time from 10% to 90% of the response to the step input.
Peak Time: The time for a system to respond to a step input and rise to peak response.
Overshoot: The amount by which the system output response proceeds beyond the desired response. It
is calculated as

where MPt is the peak value of the time response, and fv is the final value of the response.
Settling Time: The time required for the system’s output to settle within a certain percentage of the
input amplitude (which is usually taken as 2%). Then, settling time, Ts, is calculated as

You might also like