Experiment-1-GROUP 7
Experiment-1-GROUP 7
LABORATORY MANUAL
Experiment 1
Programming in MATLAB
SECTION: BSME-4B
1.1 INTRODUCTION
When you start MATLAB, the MATLAB desktop appears, containing tools (graphical user
interfaces) for managing files, variables, and applications associated with MATLAB. The first
time MATLAB starts, the desktop appears as shown in Fig. 1.1. The following important entities
in the MATLAB user interface are explained in detail.
Command Window
This is where you input commands like entering values in variables, or running scripts (m-files).
M-files are scripts that simply execute a series of MATLAB statements, or they can be functions
that also accept arguments and produce outputs. The prompt >> is an indicator where you will
input values, basic expressions and scripts.
Command History
Lines you enter in the Command Window are logged in the Command History window. In the
Command History, you can view previously used functions, and copy then execute those selected
lines.
Figure 1.1: The MATLAB Environment
Workspace Browser
The MATLAB Workspace Browser in Figure 1,2 consists of the set of variables (named arrays)
built up during a MATLAB session and stored in memory. You add variables to the workspace by
using these functions, running m-files, and loading saved workspaces.
Start Menu
The Start Menu consists of various MATLAB Toolboxes and Blocksets. These toolboxes and
blocksets are used depending on a specific application, and contain various predefined functions
and demos. The Control System Toolbox is used in this text.
Once you are familiar with the MATLAB environment, it is time to enter basic expressions. In the
command window, all commands are straightforward; just type the expressions such as entering
values in a variable or running an m-file.
Expressions typed without a variable name are evaluated by MATLAB and the result is stored and
displayed by a variable called ans. The result of an expression can be assigned to a variable name.
Variable names consist of a letter, followed by any number of letters, digits, or underscores.
MATLAB uses only the first 31 characters of a variable name and MATLAB is case sensitive.
MATLAB is so straightforward that you may enter also mathematical expressions and formulas
as you enter the variables. Notice that MATLAB display the result with 5 significant digits (default
format: format short). The commands format short e, format long, and format long e display 5
digits floating point, 15 digits fixed point, and 15 digits floating point, respectively. The first
example shows a ‘no typed variable’ expressions, answer is automatically stored in ans. The first
expression involves direct value in a variable, while the second one shows a direct mathematical
expression using the function cos. Further explanations on Math functions are explained in
Elementary Mathematics Functions.
Listing 1.1
>>13
ans =
13
>>cos(3.1416/3)
ans =
0.5
The second example shows an expression with values stored in variables a and b.
Listing 1.2
>>a= 234.56778
a =
2.3457e+002
>>b=3.1416*(cos(3.1416/6))+2
b =
4.7207
In displaying answers and expressions, the % indicates that any typed expression is converteinto a
comment while typing a semicolon, ;, after a mathematical expression, omits the MATLAB
response or does not display the result. An example is shown in basic display manipulation. The
first expression does not display the value of a1 but it is still in the workspace while the second
expression is converted into a comment.
Listing 1.3
>>a1=3.5445/64;
>>% a1=3.5445/64
Using the command fprintf you can directly manipulate the format of the output of an expression
or function. This command displays the result with a desired format on the screen or to specified
filename. The %8.4f, indicates that the output value is a float number that has 4 decimal values
and has 8 characters in length, if length of characters is less than 8 (7 in the example) the 8th would
be a space. All expressions inside the single quote sign are the ones to be displayed. The \n
indicates that the next output to be displayed (if there’s any) would be on the next line.
Listing 1.4
>>fprintf('Area of a circle is %8.4f Square meters\n',
3.1416*3^2)
Area of a circle is 28.2744 Square meters
MATLAB has several predefined variables and are listed in Table 1.1. You may try the following
variables in the Command Windowto check their functionality. There are also several commands
that perform specific functions. These commands are listed in Table 1.2. It is recommended to try
them for you to see how it works.
i or j Imaginary unit
inf Infinity
NaN Not-a-number
pi 3.14159265358…… or (π)
clear variable Clear the contents and the variable itself in the
workspace. Without the variable, it clears the
whole workspace
Listing 1.5
>>c='Manila'
c =
Manila
>>cs=[c,',Philippines']
cs =
Manila,Philippines
MATLAB treats the single value element, like in the first and second example earlier on
Expressions and Variables as a single element matrix. From the word ‘MATLAB’ which means
Matrix Laboratory, it explains why values are treated as matrices. Matrices are entered into
MATLAB by listing the elements of the matrix and enclosing them within a pair of brackets, “[
].” Elements of a single row are separated by commas or blanks, and rows are separated by
semicolons or carriage return.
>>A=[4 32 31 5]
A =
4 32 31 5
>>A=[4,32,31,5]
A =
4 32 31 5
Listing 1.7
>>B=[3;4;5]
B =
3
4
5
Combining the single column and single row matrix instructions, you can create an m x n
Listing 1.8
>>C=[1 2;3 4]
C =
1 2
3 4
The entire row or column can be addressed using colon “;”. For example, if you want to get the
first row of matrix C, follow the example below. The number 1 denotes ‘first’ and its location tells
whether it is a column or row. If the number is placed on the first position, then it denotes that the
output is an entire row and if it is placed in the second position, it denotes an entire column. In our
example, the number 1 is placed on the first position; therefore its output is the first row. Try to
interchange the colons and numbers to see the corresponding change on the output.
Listing 1.9
>>frow=C(1,:)
frow =
1 2
>>
You can also address a single element in a given matrix, we know that a matrix element can be
addressed in an expression (i,j), where i is the row and j is the column of the element. Same thing
is done here in MATLAB. For example, to get the 1st row, 2nd column element of matrix C, which
is 2, see the example below.
Listing 1.10
>>f12=C(1,2)
f12 =
2
+ Addition
- Subtraction
.* Element-by-element multiplication.
./ Element-by-element division.
.^ Element-by-element power
The inverse of a matrix, denoted by C-1 can be done by using the command >>inv(C). An example
is shown below.
Listing 1.11
>>C=[1 2;3 4]
C =
1 2
3 4
>>D=[5 6;7 8]
D =
5 6
7 8
>>C*D
ans =
19 22
43 50
>>C\D
ans =
-3.0000 -4.0000
4.0000 5.0000
>>inv(C)*D
ans =
-3.0000 -4.0000
4.0000 5.0000
>>C.*D
ans =
5 12
21 32
Transpose and Conjugate Transpose
>>E=D'
E =
5 7
6 8
Special matrices can be generated by using the functions given in Table 1.4.
Information on a particular matrix can be extracted. This can aid in certain calculations and
operations. Try these commands and see how it works. See Table 1.5 for details.
det Determinant
Manipulation and creation of matrices can be done using the following MATLAB functions. See
Tables 1.6 and 1.7. Try the following commands and see how it works.
Generating Sequences
Vectors can be generated by just specifying the first, last and the increment desired for each
element. For example, if you want to create a row vector with a first element of ‘1’ and a last
element of ‘9’ and an increment of ‘1’, just use the syntax in the example below. The default
increment is ‘1’ so even if you omit the second parameter ‘1’, >>F=(1:9), you still can get the
same result. You may try to experiment and change the increment, and see what happens.
Listing 1.13
>>F=(1:1:9)
F =
1 2 3 4 5 6 7 8 9
>>F=(1:9)
F =
1 2 3 4 5 6 7 8 9
Complex Numbers
We encounter some problems that include operations and manipulation of complex numbers.
Cases like getting the roots of a polynomial or solutions on partial fraction expansion that involves
complex roots are common. In MATLAB, imaginary numbers are represented using i or j.
Mathematical operations are straightforward, similar to operations in real numbers. As an example,
let us perform basic operations of two complex numbers.
Listing 1.14
>>(25+65j)+(30+80j) %Addition
ans =
5.5000e+001 +1.4500e+002i
>>(25+65j)/(30+80j) %Division
ans =
0.8151 - 0.0068i
We can also extract some parameters from complex numbers like phase angle and magnitude, real
part and imaginary part. As an example, we need to get the magnitude and phase angle of the
complex number 25 – j65. We have to convert the angle in degrees so we multiplied π/180 to the
answer of angle (always in radians).
Listing 1.15
>>abs(25-65i)
ans =
69.6419
>>angle(25-65i)*(180/pi)
ans =
-68.9625
>>real(25-65i)
ans
25
>>imag(25-65i)
ans
-65
Matrix Exponential
Note that a transcendental function is interpreted as a matrix function if an “m” is appended to the
function name, as in expm(A) or sqrtm(A).
Eigenvalues
The eigenvalues of a matrix A is found by using the function >>eig(A), which returns the
eigenvalues in a column vector. If A is real and symmetric, the eigenvalues will be real. But if A
is not symmetric, the eigenvalues are frequently complex in nature.
Elementary Mathematics Functions and Operators in MATLAB
Elementary math functions and operators in MATLAB are very easy to use since they are basic
and straightforward in nature. Basic operations like addition, subtraction, multiplication, division
can be represented by “ + , - , * , / ” respectively. If you want to raise a number to a certain
exponent, just simply insert ^ after the number and before the exponent. For example, if you want
to evaluate 26, just type >>2^6. For matrices or arrays, operations are different (for exponents,
multiplication and division) as stated earlier.
Some MATLAB basic math functions automatically operate element by element on an array.
Functions that operate element by element are given in Table 1.8.
cos Cosine
exp Exponential
tan Tangent
Logical Operator
MATLAB relational operators and logical operators also work on an element by element basis.
Relational operators compare two scalars and produce a 1 if the operation is true and a 0 if it is
false. For example, if you enter >>t=17>55, MATLAB will respond with t = 0. When used with
two matrices, relational operators compare corresponding matrix elements. For example, >>L = D
<= X will check every element of D against the corresponding element of X. If the element of D
is less than or equal to the corresponding element of X, the corresponding element of L will be 1.
Otherwise, the corresponding element of L will be zero. The logical operators & for logical AND,
| for logical OR, and ~ for logical NOT all return 1 for logical TRUE and 0 for logical FALSE. An
example is shown below.
Listing 1.16
>>H=[1 3 5 7 9];
>>I=[0 2 3 4 5];
>>J=[2 2 6 3 4];
>>lgcal1=H<I
lgcal1 =
0 0 0 0 0
>>lgcal2=H>I
lgcal2 =
1 1 1 1 1
>>lgcal3=(H>I)&(H>=J)
lgcal3 =
0 1 0 1 1
Files that contain code in the MATLAB language are called m-files. You create m-files using a
text editor, then use them as you would any other MATLAB function or command.
1. Scripts, which do not accept input arguments or return output arguments. They
operate on data in the workspace.
2. Functions, which can accept input arguments and return output arguments.
If you're a new MATLAB programmer, just create the m-files that you want to try out in the
current directory. As you develop more of your own m-files, you will want to organize them into
other directories and personal toolboxes that you can add to MATLAB search path. If you duplicate
function names, MATLAB executes the one that occurs first in the search path. Each script file
should have a name that ends in “.m” The commands in the script file are executed in the
MATLAB environment by simply entering the name of the script file without the extension “.m.”
Creating Functions
Function files are m-files that are very similar to script files. The first major difference is that the
first line of a function file begins with the word function, followed by a statement identifying the
name of the function and the input and output argument in the form:
Control Flow
In your functions or scripts, it is common that you include control flow commands. MATLAB
control flow is given in Table 1.9. The control flow commands for, while, and if are statements
similar to those used in many computer languages to produce conditional statements or loops.
Every for, while, and if statements must be matched with an end statement. The break command
can be used to terminate the execution of a loop permanently. The if statement can be used in
conjunction with the nargin, nargout, and error functions to perform error checking of a function.
Inside a function file, nargin and nargout are equal to the number of input and output arguments,
respectively, that were used in function call. The function error(‘message’) returns control to the
keyboard and displays message. For more information regarding the commands, please type
>>help <command>.
statement
of times
number of times
MATLAB can create high-resolution, publication-quality 2-D, 3-D, linear, log, semilog, polar,
bar chart and contour plots on plotters, dot-matrix printers, and laser printers. Some of the 2-D
graph types are plot, loglog, semilogx, semilogy, polar, and bar. The command grid adds a grid to
the graph, and the command title (‘text’), xlabel(‘text’), ylabel(‘text’),and text(‘text’) can be used
for labeling and placing text on the graph. MATLAB provides automatic scaling. The function
axis ([xmin, xmax, ymin, ymax]) enforces manual scaling.
As an example, let us plot a sinusoidal function, let y = 2sin x , where x is the abscissa
(an angle) and y is the ordinate. Take note that angles are in radians. The listing is shown
below.
Listing 1.17
>>x=(0:0.002:2*pi);
>>y=2*sin(x);
>>plot(x,y); title('Sinusoidal waveform');
The functions to be presented are basic and are commonly used in control systems applications.
These functions are not used directly for solving control system problems but rather application of
these commands will greatly help in solving them.
Polynomials
Polynomials can be represented as row vectors containing the coefficients. As an example, the
polynomial s3 + 32s2 + 32 can be represented as:
Listing 1.18
>>x=[1 32 0 32]
x =
1 32 0 32
>>
The first element of the vector is the coefficient of the highest exponent while the last is the
coefficient of the lowest exponent. A ‘0’ is included because there is no s on the polynomial.
Polynomials can also be represented in a factor form of its roots such as :
P =s(s+2)(s-4)(s+5) , which can be written using the function poly(), as shown below.
Listing 1.19
>>x=poly([0 –2 4 –5])
x =
1 3 -18 -40 0
For a given characteristic polynomial, its roots can be obtained by using the function
roots().
Listing 1.20
>>roots([1 3 -18 -40 0])
ans =
0
4.0000
-5.0000
-2.0000
Two polynomials can also be multiplied and divided using the conv() and deconv()
functions.
>>x = [1 2 1];
>>y = [2 5];
>>m = conv(x,y)
m =
2 9 12 5
>>n = deconv(x,y)
n =
0.5000 -0.2500
Other important functions used in control engineering analysis and design are shown in
Table 1.10.
Table 1.10:Other basic functions for control engineering applications.
a) AB
b) BA
c) ATA
d) ATA + C
e) Show that I3C = CI3 = C
f) Eigenvalues of C
8. Generate . Define x as a vector of linearly spaced values between 0 and
2π. Use π/100 as an increment of between the values.
11) Augment the constant matrix in No. 9 to the coefficient matrix also in No. 9. Determine the
Reduced Row Echelon Form of this augmented matrix by using the function rref. What is the
significance of this result?
12) Determine the size of the matrix generated in No. 9 using the function size.
13) Determine the length of the matrix generated in No. 9 using the function length
14) What is the difference between size and length?
The difference between the two functions, is that these is that the size function
returns the row and columns {1 4} of provided matrix, while the length function
return only the row or column that is bigger (4)
4.0 References