Sie sind auf Seite 1von 10

THE UNIVERSITY OF GAZIANTEP, FACULTY OF ENGINEERING

DEPARTMENT OF ELECTRICAL AND ELECTRONICSENGINEERING


AUTOMATIC CONTROL SYSTEMS (EEE 352) LABORATORY, EXPERIMENT 01

INTRODUCTION TO MATLAB: MATrix LABoratory


1. Aim of the experiment
The purpose of this experiment is
a) to give an introduction to MATLAB,
b) to let the students read and do the exercises given in the documents called MATLAB Getting
Started Guide.PDF
c) to be familiar to interactive environment of MATLAB for numerical computation, visualization,
and programming.
2. Introduction
MATLAB provides an integrated software environment with commands for matrix analysis, control
system design and analysis, digital signal processing, system identification, robust control,
optimization, etc.
MATLAB is an abbreviation for "MATrix LABoratory."While other programming languages
mostly work with numbers one at a time, MATLAB is designed to operate primarily on whole
matrices and arrays.
It is strongly suggested that the students should have MATLAB installed and should do the steps
and type the commands indicated in the following text. When MATLAB starts the desktop appears
in its default layout, Figure 1.

Current Folder (Activated)


Access your files.

Current
Folder
Files in
your files.

Workspace
Explore data that
you create or
import from files.

Command Window
Enter commands at the
command line, indicated
by the prompt (>>).

Command History
View or rerun commands
that you entered at the
command line.

Figure 1: The default layout of MATLAB starting desktop.


Exp.1:1

MATLAB is extremely easy to use. A quick introduction to learn how to use MATLAB can be
obtained by typing demo command at the command line, indicated by the prompt (>>).
demo
at Command Window. Typing demo brings up a menu of demonstrations. An on-line Help facility
is also available, providing information on most MATLAB topics. To get a list of Help topics, type
help
gives a long list stars with
matlab\general
- General purpose commands.
matlab\ops
- Operators and special characters.
matlab\lang
- Programming language constructs.
matlab\elmat
- Elementary matrices and matrix manipulation.
:
If
help elmat
is typed then a list contains elementary matrices and matrix manipulation will be seen. To get Help
on a specific topic, type help topic. For examples,
help inv
provides HELP information on the use of the Matrix inverse,
help control
lists comments exists in Control System Toolbox.
MATLAB is usually used in command-driven mode; when single-line commands are entered
MATLAB process them immediately and displays the results. MATLAB is also capable of
executing sequences of commands that are stored in files. Together, these two modes form an
interpretive environment.
3. Variables, Operators, and Numerical Data Types in MATLAB
The variables begin with an alphabetic character and are case sensitive, thus the variable A is
different from a.
a=2
b=5, c=ok, d=1.3;
Default output variable is ans.
All MATLAB variables are multidimensional arrays, no matter what type of data. For instant b
variable is stored as b(1,1)=5. Type the following comments notice the result and massages.
a(1,1)
a(1,2)
a(1,0)
If a statement ended with a semicolon, (;), MATLAB performs the computation, but suppresses the
display of output in the Command Window.
a=2;
Built-in constants are pi, i, j, and Inf.
The comment clear removes variables and who lists variables.
Special characters are [ ] ( ) { } ; % : = . @. For example % is used to add comments
T=0.2; % is the system time constant.
Arithmetic operators are + - / \ ^ .\ . / .* .^. Relational operators are < > <= >= == ~=.
Logical operators are | & || && true false. Operator precedence are ( ) { } [ ] ->Arithmetic
-> Relational -> Logical.
Do not use special characters, operators, or keywords in variable names.
The notations are typed similar to variables;
Exp.1:2

x=3; y=4.5; z= 0.5e+3;


The numeric manipulations are;
y=4.5; x=round(y);
format long % or format compact
Complex numbers have both real and imaginary parts, where the imaginary unit is the square root of
1, i.e., -1.
To represent the imaginary part of complex numbers, use either i or j:
x=5+6i, % or x=5+6j
4. Arrays and Plots in MATLAB
Array construction: Consider the problem of computing values of the cosine function over one half
of its period, namely: y cos( x) , x [0, ]. Since it is impossible to compute cos(x) at all points
over this range (there are infinite number of points), we must choose a finite number of points. In
doing so, we are sampling the function. To pick some number, lets say evaluate every 0.1 in this
range, i.e.
let x={0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, }. To create an array in MATLAB, all
you have to do is to start with a left bracket enter the desired values separated by comas or spaces,
and then close the array with a right bracket. In MATLAB to create this vector is relative easy:
x=[0 0.1*pi 0.2*pi 0.3*pi 0.4*pi 0.5*pi 0.6*pi 0.7*pi 0.8*pi 0.9*pi pi]; % or x=0:0.1*pi:pi;
To evaluate the function y at these points we type:
y=cos(x)
Note, how MATLAB finds the values for x and stores them in the array y.
Plots Data: One of the most useful abilities of MATLAB is the ease of plotting data. The plot
function has different forms, depending on the input arguments.
If y is a vector, plot(y) produces a piecewise linear graph of the elements of y versus the index of
the elements of y.
If you specify two vectors as arguments, plot(x,y) produces a graph of y versus x.
In MATLAB we can plot two and three-dimensional graphics. Here we will only study twodimensional plots.
Example 4.1: Assume that we want to plot y cos( x) for x [0, 2 ] with 0.1 step size.
To plot those we use the command plot like this:
x=0:0.1*pi:2*pi; y=cos(x); plot(x,y);
Then we will see a new window that contains the following Figure 2 (a):
Plot of the Cosine Function
1

0.5

0.5
y=cos(x)

-0.5

-0.5

-1

-1
0

(a)
(b)
Figure 2: y=cos(x) function; (a) without and (b) with axis labels and title.
Exp.1:3

The label of axes and a title can be added, Figure 2 (b):


xlabel('x'), ylabel('y=cos(x)'), title('Plot of the Cosine Function')
To add plots to an existing figure, use
hold % or hold on
5. Vectors and Matrix in MATLAB
MATLAB environment uses the term matrix to indicate a variable containing real or complex
numbers arranged in a two-dimensional grid. An array is, more generally, a vector, matrix, or higher
dimensional grid of numbers. All arrays in MATLAB are rectangular, in the sense that the
component vectors along any dimension are all the same length.
A vector is a one-dimensional array. To create an array with four elements in a single row, separate
the elements with either a comma (,) or a space type,
a = [1 2 3 4]
This type of array is a row vector. It can be converted to a column vector by typing transpose (the
apostrophe , although often rendered as ');
a = [1 2 3 4] % or b=a'
A matrix is two-dimensional array often used for linear algebra.
To create a matrix that has multiple rows, separate the rows with semicolons.
A = [1 2 3; 4 5 6; 7 8 10];
There are various matrix functions that can be done in MATLAB, some of them are:
To find the determinant, det(),
A=[1 2 3;4 5 6;7 8 9]; a=det(A)
To find the inverse, inv(),
A=[1 5 3;4 5 10;7 8 50];
b=inv(A)
Some of matrix functions defined in MATLAB are given in Table 1.

Command
det(A)
eig(A)
[x,d]=eig(A)
expm(A)
norm(A)
norm(A,1)
norm(A,2)

Table 1: Matrix functions in Matlab


Commends
Command
Determinant
norm(A,inf)
Eigenvalues
norm(A,p)
Eigenvectors
norm(A,fro)
Matrix exponential.
poly(A)
Matrix and vectors norm.
rank(A)
1-norm
sqrtm(A)
2-norm (Euclidean)
trace(A)

Commends
Infinity norm
p-norm (vectors only)
f-norm
Characteristic polynomial
Rank
Matrix square root
Sum of diagonal elements

6. Evaluating Polynomials in MATLAB


Finding the roots of a polynomial is a problem that arises in many disciplines. MATLAB solves this
problem and provides other polynomial manipulation tools as well. In MATLAB, a polynomial is
represented by a row vector of its coefficients in descending order. For example the polynomial
P( x) x 3 x is entered as
Px=[1 0 -1 0]
Note that terms with zero coefficients must be included.
The roots of a polynomial can be found by the function roots:
q=roots(Px)
If we have the roots we can find the polynomial by using the function poly:
Px1=poly(q)
Exp.1:4

To multiply two polynomials, P1 ( x) x 4 2 x 3 5 x 10 and P2 ( x) x 1 we use the command


conv;
p1=[1 -2 0 5 10];
p2=[1 1];
p=conv(p1,p2)
To divide two polynomials P1 ( x) 2 x 3 1 and P2 ( x) x 2 x 2 we use the command deconv:
p1=[2 0 0 1];
p2=[1 1 2];
[q,r]=deconv(p1,p2)
The differentiation of a polynomial is found by using the function polyder:
pd=polyder(p)
Example 6.1: Assume the following polynomial needs to be evaluated starts at x=-2 and ends at 2
with 0.1 step size.
(1)
P ( x) x 3 x
The polynomial P(x) is defined in MATLAB by row vectors containing the polynomial coefficients
in order of descending degree. Thus the polynomial coefficients are;

P ( x) x 3 x

P( x) a1 x 3 a 2 x 2 a3 x a 4
1x 3 0 x 2 1x 0

The MATLAB comments are;


Px=[1 0 -1 0] % The polynomial
x=-2:0.1:2 % x variable starts at x=-2 and ends at 2 with 0.1 step size.
y=polyval(Px,x)
Example 6.2: Assume a third order curve need to be fitted the results of an experiment starts x=-2 to
2 with 0.3 step size is given as;
y=[-6 -3.213 -1.344 -0.231 0.288 0.375 0.1920 -0.099 -0.336 -0.357 0 0.897 2.496 4.959].
The MATLAB comments are;
x=[ -2.0 -1.7 -1.4 -1.1 -0.8 -0.5 -0.2 0.1].
y=[-6 -3.213 -1.344 -0.231 0.288 0.375 0.1920 -0.099 -0.336 -0.357 0 0.897 2.496 4.959]
Pm=polyfit(x,y, 3)
7. M Files and Programming in MATLAB
The files that contain MATLAB statements are called M Files because they have a file type of .m
as the last of the filename. For example, a file named inv.m contains MATLAB statements that
evaluate Matrix inverse.
There are two type of M Files exist or can be developed.
Script M-Files;
a) Automate a series of steps,
b) Share workspace with other scripts and the command line interface.
Script M Files consist of sequence of normal MATLAB statements, possibly including references
to other M Files. Script M File can call itself recursively.
Second types of M File are called as function M Files.
Exp.1:5

Function M-Files;
a) Extend the MATLAB language,
b) Can accept input arguments with parentheses ( ) and return output arguments with the brackets [],
c) Store variables in internal workspace.
function [out1, out2, ...] = funname(in1, in2, ...) defines function funname that accepts inputs in1,
in2, etc. and returns outputs out1, out2, etc
Function M-Files allow new function to be added to the existing function to create new functions
that solve user specific problems.
The MATLAB product provides a powerful programming language, as well as an interactive
computational environment. It is very easy to create the program files in MATLAB.
A MATLAB program;
a) always has one script M-File,
b) uses built-in functions as well as new functions defined in function M-files,
c) saved as<filename>.m,
d) to run: filename only (no .m extension)
>> <filename>
e) created in Editor / Debugger.
Note: It needs to be saved in your directory not in C:\ ...\Documents \MATLAB. To change and
activate your directory as follows;

Change Current Folder (Activated)


To save and access your files.

Otherwise if you save your files in C:\ ...\Documents \MATLAB they may be conflicted with
existing MATLAB files.
Example 7.1: The M File for Example 6.1 and the graphical result are;
% M File for Example 6. 1
clear all % clear all is used to clear variables and functions from memory.
Px=[1 0 -1 0];
x=-2:0.3:2;
y=polyval(Px,x);
plot(x,y)
xlabel('x'),ylabel('y'),grid

Exp.1:6

6
4

2
0
-2
-4
-6
-2

-1

0
x

Figure 3: The y output for y x 3 x .


Example 7.2: Consider the following nonlinear function need to be evaluated in the interval 0 x 1
with the step size 0.002.

1
1

6
2
(( x 0.3) 0.1) (( x 0.9) 2 0.04)

Let create an M function to represent the nonlinear function


function y = nonfunc1(x)
% this file models the nonlinear function given in example 7.2
y = 1./((x-.3).^2 + 0.1) + 1./((x-.9).^2 + .04) - 6;
The M function has to be named saved with the function name, here, nonfunc1.m
(Note: It needs to be saved in your directory not in MATLAB and your directoy )
The following M file is written to evaluate M function nonfunc1.m in the interval 0 x 1 with the
step size 0.002. Note both these files has to save in your active current folder.
% M File for Example 7. 2
clear all % clear all is used to clear variables and functions from memory.
x = 0:0.02:1; y = nonfunc1(x);
plot(x,y), xlabel('x'), ylabel('y'), grid
8. Pre-Lab: Preparation tasks for MATLAB, to be solved BEFORE the lab
You must read this section in its entirety and answer all pre-lab questions before showing up for lab.
You must turn in your answers to the pre-lab questions at the beginning of the lab period. If you
answer the pre-lab questions incorrectly, the teaching assistant may refuse to allow you to complete
the lab. Therefore, it is in your best interest to confer with your lab partners to verify that your
answers and understanding of the pre-lab material is correct.
Read and use reference [1], MATLAB Getting Started Guide to do the following tasks.
Task 8.1: Explain the following commands and write returns from the workspace
A = [1 2 3; 4 5 6; 7 8 10]
P= A*inv(A)

Exp.1:7

B=A.^3
C= [3+4i 0 0, 0 4+3j 0; 0 0 -10]
A(1:3,2)
max(A);
D=[A,B]
E= magic(4)
La=eig(A)
Lc=eig(C)

Task 8.2: Write an M-File to


a) Define the vector x starts from 0 with 0.01 step size to 2* and y = sin(x).
b) Plot the graph y versus x.
Task 8.3: Explain the commands given in the following M-file and write returns from the
workspace
% M File 1 for Task 8.3
x = 0:pi/100:2*pi;
y = sin(x);
subplot(2,1,1); plot(x,y)
ylabel('sin(x) ')
xlabel('time(sec) ')
y2 = cos(x);
subplot(2,1,2); plot(x,y2)
ylabel('cos(x) ')
xlabel('time(sec) ')

Task 8.4: Explain the commands given in the following M-file and write returns from the
workspace
% M File for Task 8.4
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
hold on
y2 = cos(x);
plot(x,y2,'r:')
legend('sin','cos')
ylabel('sin(x) & cos(x) ')
title('Plot of the Sine & Cosine Functions')

Task 8.5: Write an M-File to


a) Find the roots of the polynomial P1 ( x) x 2 3x 2
b) Create a polynomial P2 ( x) with roots in 1, -3, 5 and 2.
c) Multiply the polynomials Pm ( x) P1 ( x) P2 ( x) defined in (a) and (b).
d) Divide the polynomials Pd ( x)

P1 ( x)
defined in (a) and (b).
P2 ( x)

Task 8.6: Use help to read information for residue built in function.
Write an M-File to get the fraction expansion of
s 2 3s 2
P( s ) 4
s 6 s 3 5s 2 2 s
Exp.1:8

where s is Lablace operator.


Task 8.7: Write an M-File to solve x=[ x1 x2 x3]T for the following the equation system Ax B ;
5 6 0 x1 6
3 6 1 x 1

2
8 7 9 x3 4
Task 8.8:
Write an M-Function to model and M-File to solve the differential equation given in equation (1)
and Plot x(t) for the time frame 0 t 10 sec.
1 x1
x1 0
x 3 5 x ,
2
2

x1 (0) 1
x (0) 0
2

(1)

9. Tasks to be done and to be given in lab report


Task 9.1:
The differential equation given in equation (2)

x1 0 6 1 x1
x1 (0) 1
x 6

2 16 x2 , x2 (0) 1
2

x3 5 20 10 x3
x3 (0) 1
and has x(t) solution given in equation (3)
x(t ) x(0)e tA .
write an M-File to Plot x1(t), x2(t) and x3(t) for the time frame 0 t 5 sec.

(2)

(3)

Task 9.2:
a) Write an M-Function to model and an M-File to solve the differential equation given in equation
(4) and Plot x(t) for the time frame 0 t 5 sec.

x1 0 6 1 x1
x 6
2 16 x2 ,
2
x3 5 20 10 x3

x1 (0) 1
x (0) 1
2
x3 (0) 1

(4)

b) Compare the results of Task 9.1 with Task 9.2 a).


Task 9.3:
a) Write an M-Function to model the differential equation given in equation (5)
1 x1 0
x1 0
x 2 2 x 1 u

n 2
2 n

(5)

b) Write an M-File to solve model of the differential equation in equation (5) for n = 4 rad/sec,
=0.5, u = 10, x(0) = [0;0] and for the time frame 0 t 10/(n) sec.
c) Plot x(t)=[x1(t), x2(t)] for the time frame of defined t.
Exp.1:9

Task 9.4: Consider the following block diagram where the blocks dynamics given in terms of the
fraction expansion in equation (6).

10( s 1)
( s 3)
, G p ( s)
( s 3)
s ( s 1)(s 10)
where s is Laplace operator.
R(s)
Gc ( s )

Reference

(6)
Gc(s)
Controller

U(s)

Gp(s)

Y(s)
Output

Plant

Figure 4: An open loop control system.

a) Write an M-Function to model blocks controller and plant in (6).


b) Write an M-Function to have the following ratio;

Y (s)
Gc ( s )G p ( s)
R( s )
(Hint: type help tf and series in command window read the information)

(7)

10. Lab report


Before the next lab session, each group member is responsible to write and submit his/her laboratory
reports. The report should log the programs and results from the experiment with your own
interpretations, observations and conclusions. You should try to perform all MATLAB commands
and solve all questions in the manual. The report must be type-written do not have unnecessary
pages.
Summarize your observations and attach relevant MATLAB scripts, diagrams and plots.
References
[1] MATLAB Getting Started Guide. PDF, The MathWorks, Inc., 19842013 3 Apple Hill Drive
Natick, MA 01760-2098, USA.
[2] Ogata K., Modern Control Engineering, Pearson Education Inc.,Prentice Hall,5th Ed., 2010.
[3] Dorf R. C. and Bishop R. H., Modern Control Systems, Pearson, 2011.
[4] Web pages:
http://www.mathworks.com
http://www.engin.umich.edu/group/ctm/
http://www.math.mtu.edu/~msgocken/intro/intro.html

Exp.1:10

Das könnte Ihnen auch gefallen