1.1 Description: MATLAB Primer

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

EE 324 Linear Control Systems S.

Redif 01/03/2010
MATLAB Primer
1.1 Description
Using MATLAB to model systems and visualise data can help identify subtle phenomena quickly.
Technical professionals worldwide rely on MATLAB to accelerate their research, compact the
time invested in analysis and development, reduce project costs, and produce effective
solutions. The combination of the intuitive MATLAB interface, language, and the built-in math and
graphics functions make MATLAB the preferred platform for development purposes. MATLAB
includes tools for:

Data acquisition, analysis and exploration
Visualisation and image processing
Algorithm prototyping and development
Modelling and simulation
Programming and application development
1.2 Overview
MATLAB handles a range of computing tasks in engineering and science, from data acquisition
and analysis to application development. The MATLAB environment integrates mathematical
computing, visualization, and a powerful technical language. Built-in interfaces let you quickly
access and import data from instruments, external databases and programs. In addition, MATLAB
lets you integrate external routines written in C, C++ and Java with your MATLAB applications.

MATLAB is used in a variety of application areas, including signal/image processing, control system
design, finance, and instrumentation. The open architecture makes it easy to use MATLAB and
companion products to explore data and create custom tools that provide early insights and
competitive advantages. Key Features:

Numeric computing for quick and accurate results
Graphics to visualise and analyse your data
Interactive language and programming environment
Tools for building custom GUIs
Conversion and interfaces to external languages, such as C, C++, and Java
Support for importing data from files and external devices and for using low-level file I/O.
1.3 MATLAB Basics
When MATLAB is first launched, its command window appears. When MATLAB is ready to accept an
instruction or input a command prompt >> is displayed in the command window. Nearly all
MATLAB activity is initiated at the command prompt. Entering instructions at the command prompt
generally results in the creation of an object or objects. Many classes of objects are possible,
including functions and strings, but usually objects are just data. Objects are placed in what is called
the MATLAB workspace. If not visible, the workspace can be viewed in a separate window by typing

>> workspace

at the command prompt. The workspace provides important information about each object,
including the objects name, size and class. Another way to view the workspace is the whos
command. When whos is typed at the command prompt, a summary of the workspace is printed in
the command window. The who command is a short version of whos that reports only the names
of workspace objects.

EE 324 Linear Control Systems
2

Several functions exist to remove unnecessary data and help free system resources. To remove
specific variables from the workspace, the clear command is typed, followed by the names of the
variables to be removed. Just typing clear removes all objects from the workspace. Additionally,
the clc command clears the command window, and the clf command clears the current figure
window.

Perhaps the most important and useful command for new users is help. To learn more about a
function, simply type

>> help

followed by the function name. Helpful text is then displayed in the command window. The obvious
shortcoming of help is that the function name must first be known. This is especially limiting for
MATLAB beginners. Fortunately, help screens often conclude by referencing related or similar
functions. These references are an excellent way to learn new MATLAB commands. The lookfor
command helps locate MATLAB functions based on a keyword search. Simply type lookfor
followed by a single keyword, and MATLAB searches for functions that contain that keyword.
MATLAB also has comprehensive HTML-based help (Menu: Help -> MATLAB Help). The HTML help is
accessed by using MATLABs integrated help browser, which also functions as a standard web
browser. The HTML help facility includes a function and topic index as well as full text-searching
capabilities. Since HTML documents can contain graphics and special characters, HTML help can
provide more information than the command-line help.
1.4 Basic MATLAB Operations
MATLAB can function as a simple calculator, working as easily with complex numbers as with real
numbers. Scalar addition, subtraction, multiplication, division, and exponentiation are accomplished
using the traditional symbols

+ addition
- subtraction
* multiplication
/ division
^ exponentiation

Since MATLAB predefines i = j = 1, a complex constant is readily created using Cartesian
coordinates; e.g.
>> z = -3-j*4
z = -3.0000 4.0000i

assigns the complex constant -3-j4 to the variable z. The real and imaginary components of z are
extracted by using the real and imag operators. In MATLAB, the input to a function is placed
parenthetically following the function name

>> z_real = real(z);
>> z_imag = imag(z);

When a line is terminated with a semicolon (;), the statement is evaluated but the results are not
displayed to the screen. This feature is useful when one is computing intermediate results, and it
allows multiple instructions on a single line. Although not displayed, the results z_real = 3 and
z_imag = 4 are calculated and available for additional operations such as computing |z|. There are
many ways to compute the modulus, or magnitude, of a complex quantity. Trigonometry confirms
EE 324 Linear Control Systems
3

that |z| = |3 j4| = (3)
2
+(4)
2
. The MATLAB sqrt command provides one way to
compute the required square root.

>> z_mag = sqrt(z_real^2+z_imag^2)
z_mag = 5

The same result is also obtained by computing |z| = zz

. In this case, complex conjugation is


performed by using the conj command.

>> z_mag = sqrt(z*conj(z))
z_mag = 5

More simply, MATLAB computes absolute values directly by using the abs command.

>> z_mag = abs(z)
z_mag = 5

In addition to magnitude, polar notation requires phase information. The angle command provides
the angle of a complex number.

>> z_rad = angle(z)
z_rad = -2.2143

MATLAB expects and returns angles in a radian measure. Angles expressed in degrees require an
appropriate conversion factor.

>> z_deg = angle(z)*180/pi
z_deg = -126.8699

Notice, MATLAB predefines the variable pi = . It is also possible to obtain the angle of z using a
two-argument arc-tangent function, atan2.

>> z_rad = atan2(z_imag,z_real)
z_rad = -2.2143

MATLAB supports a full complement of trigonometric functions: standard trigonometric functions
cos, sin, tan; reciprocal trigonometric function sec, csc, cot; inverse trigonometric functions
acos, asin, atan, asec, acsc, acot; and hyperbolic variations cosh, sinh, tanh, sech, etc.

In MATLAB, base-10 and base-e (natural) logarithms are computed by using the log10 and log
commands, respectively.

>> log(-1)
ans = 0 + 3.1416i.
1.5 Introduction to Vectors in MATLAB
MATLAB is a software package that makes it easier for you to enter vectors and matrices, and manipulate
them. The interface follows a language that is designed to look a lot like the notation use in linear algebra.
Almost all of MATLABs basic commands revolve around the use of vectors and matrices. To simplify the
creation of vectors, you can define a vector by specifying the first entry, an increment, and the last entry.
MATLAB automatically calculates how many entries are needed and their values.

EE 324 Linear Control Systems
4

Example: Create a vector whose entries are 0, 2, 4, 6, and 8. You can type in the following line:

>> 0:2:8
ans =
0 2 4 6 8

Negative and noninteger step sizes are also permissible.

>> k = 11:-10/3:0
k = 11.0000 7.6667 4.3333 1.0000

If a step size is not specified, a value of one is assumed.

>> k = 0:11
k = 0 1 2 3 4 5 6 7 8 9 10 11

MATLAB also keeps track of the last result. In the previous example, a variable "ans" is created.
Example: Determine the transpose of the previous result. Enter the following:

>> ans

ans =
0
2
4
6
8

The single quote () performs the complex conjugate transpose operation. In this way, row vectors
become column vectors and vice versa, in addition, each element is replaced by its complex
conjugate. If the transpose of a vector or matrix is required without complex conjugation, then the
command . is used instead. Example:

v = [1-j 2+3*j 3-5*j 4 5];

>> v'

ans =

1.0000 + 1.0000i
2.0000 - 3.0000i
3.0000 + 5.0000i
4.0000
5.0000

>> v.'

ans =

1.0000 - 1.0000i
2.0000 + 3.0000i
3.0000 - 5.0000i
4.0000
5.0000
EE 324 Linear Control Systems
5


MATLAB will allow you to look at specific parts of the vector. If you want to only look at the first three
entries in a vector you can use the same notation you used to create the vector:

>> v(1:3)
ans =
0 2 4

>> v(1:2:4)
ans =
0 4

>> v(1:2:4)'
ans =
0
4

Once you master the notation you are free to perform other operations, for example, subtraction:

>> v(l:3)-v(2:4)
ans =
-2 -2 -2.
1.6 Vector Functions
MATLAB makes it easy to create vectors and matrices. The real power of MATLAB is the ease in
which you can manipulate your vectors. It is assumed that you know the basics of defining, indexing
and manipulating vectors.

a. Subtraction and Addition
We will define two vectors and add and subtract them:

>> v = [1 2 3]'
v =
1 2 3
>> b = [2 4 6]'
b =
2
4
6

Now add the two vectors and then subtract one from the other:
>> v+b
ans =
3
6

>> v-b
ans =
-1
-2
-3

Note that the dimensions of the arrays to be added or subtracted must agree, e.g. a row vector cannot be
added to a column vector.
EE 324 Linear Control Systems
6


b. Multiplication and Division
As with addition, multiplication of arrays must follow strict rules. The number of columns of the array on
the left must be equal to the number of rows of the array on the right of the multiplication symbol. So,
given the vector definitions above, the following MATLAB code would be erroneous and MATLAB will
produce an error message:

>> v*b
Error using ==> *
Inner matrix dimensions must agree.

The correct operations are:

>> v*b'
ans =
2 4 6
4 8 12
2 12 18
and

>> v'*b
ans =
28

In MATLAB, you can also perform "element-wise" operations. For example, suppose you want to
multiply each entry in vector v with its corresponding entry in vector b, i.e., v(l)*b(l),
v(2)*b(2), and v(3)*b(3). Then you must use the instruction ".*", thus:

>> v.*b
ans =
2
8
18

>> v./b
ans =
0.5000
0.5000
0.5000

c. Non-Linear Operations
If you pass a vector to a predefined math function, it will return a vector of the same size, and each
entry is found by performing the specified operation on the corresponding entry of the original
vector:

>> sin(v)
ans =
0.8415
0.9093
0.1411

>> log(v)
ans =
0
EE 324 Linear Control Systems
7

0.6931
1.0986

The ability to work with these vector functions is one of the advantages of MATLAB. Now complex
operations can be defined that can be done quickly and easily. In the following example a very large
vector is defined and is used as the input argument to math functions.

>> x = [0:0.1:100]
x =
Columns 1 through 7
0 0.1000 0.2000 0.3000 0.4000 0.5000 0.6000

... (most of the output has been purposefully deleted here)

Columns 995 through
1001 99.4000 99.5000 99.6000 99.7000 99.8000 99.9000 100.0000

>> y = sin(x).*x./(l+cos(x));

Example: Consider finding the three cube roots of 1, w
3
= 1 = c
(n+2nk)
for integer k. Taking
the cube root of each side yields w = c
](n+2nk)/3
. To find the three unique solutions, use any three
consecutive integer values of k and MATLABs exp function.

>> k = 0:2;
>> w = exp(j*(pi+2*pi*k)/3)
w = 0.5000 + 0.8660i -1.0000 + 0.0000i 0.5000 0.8660i

Finding the 100 unique roots of 1
100
w is just as simple.

>> k = 0:99;
>> w = exp(j*(pi+2*pi*k)/100);

A semicolon concludes the final instruction to suppress the inconvenient display of all 100 solutions.
To view a particular solution, the user must specify an index. For example, the fifth element of w is
extracted using an index of 5.

>> w(5)
ans = 0.9603 + 0.2790i

Notice that this solution corresponds to k=4. Since k is also a vector, it can likewise be indexed. In
this way, we can verify that the fifth value of k is indeed 4.

>> k(5)
ans = 4

It is also possible to use a vector index to access multiple values. For example, index vector 98:100
identifies the last three solutions corresponding to k = [97, 98, 99].

>> w(98:100)
ans = 0.9877 0.1564i 0.9956 0.0941i 0.9995 0.0314i

Vector representations provide the foundation to rapidly create and explore various signals.
Consider the simple 10 Hz. sinusoid described by (t) = sin(2n10t +n/6). Two cycles of this
EE 324 Linear Control Systems
8

sinusoid are included in the interval 0 t < 0.2. A vector t is used to uniformly represent 500
points over this interval.

>> t = [0:500-1]*0.2/500;

Next, the function (t)

is evaluated at these points.

>> f = sin(2*pi*10*t+pi/6);

The value of (t) at t = 0 is the first element of the vector and is thus obtained by using an index
of 1.

>> f(1)
ans = 0.5000

Unfortunately, MATLABs indexing syntax conflicts with standard equation notation. That is, the
MATLAB indexing command f(1) is not the same as the standard notation (1) = (t)
|t=1
. Care
must be taken to avoid confusion; remember that the index parameter rarely reflects the
independent variable of a function.
1.7 Introduction to Matrices in MATLAB
A basic introduction to defining and manipulating matrices is given here. It is assumed that you
know the basics on how to define and manipulate vectors using MATLAB. Defining a matrix is similar
to defining a vector. To define a matrix, you can treat it like a column of row vectors (note that the
spaces are required!):
Example: To define a matrix

>> A = [1 2 3; 3 4 5; 6 7 8]
A =
1 2 3
3 4 5
6 7 8

You can also treat it like a row of column vectors:

>> B = [[1 2 3]' [2 4 7]' [3 5 8]']
B =
1 2 3
2 4 5
3 7 8

As mentioned before, the notation used by MATLAB is the standard linear algebra notation you
should have seen before. Matrix-vector multiplication can be easily done. You have to be careful,
though, your matrices and vectors have to have the right size!

>> v = [0:2:8]
v =
0 2 4 6 8

>> A*v(l:3)
??? Error using ==> mtimes
Inner matrix dimensions must agree.
EE 324 Linear Control Systems
9


Once you are able to create and manipulate a matrix, you can perform many standard operations on it.
For example, you can find the inverse of a matrix. You must be careful, however, since the
operations are numerical manipulations done on digital computers. In the example, the matrix A is not a
full matrix, but MATLAB will still return a matrix.

>> inv(A)

Warning: Matrix is close to singular or badly scaled. Results may be
inaccurate. RCOND = 4.565062e-18

ans =
1.0e+15 *

-2.7022 4.5036 -1.8014
5.4043 -9.0072 3.6029
-2.7022 4.5036 -1.8014

Note: MATLAB is case sensitive. This is another potential source of problems when you start building
complicated algorithms; e.g.:

>> inv(a)
??? Undefined function or variable a.

Other operations include finding an approximation to the eigenvalues of a matrix. There are two
versions of this routine, one just finds the eigenvalues, the other finds both the eigenvalues and the
eigenvectors.
If you forget which one is which, you can get more information by typing help eig at the MATLAB prompt.

>> eig(A)
ans =
14.0664
-1.0664
0.0000

>> [v,e] = eig(A)

v =
0.2656 0.7444 0.4082
0.4912 0.1907 -0.8165
0.8295 -0.6399 0.4082

e =
14.0664 0 0
0 -1.0664 0
0 0 0.0000

>> diag(e)
ans =
14.0664
-1.0664
0.0000

There are also routines that let you find solutions to equations. For example, if Ax = b, and you want to
EE 324 Linear Control Systems
10

find x, a slow way to find x is to simply invert A and perform a left multiply on both sides (more on that
later). It turns out that there are more efficient and more stable methods to do this (ITU decomposition
with pivoting, for example). MATLAB has special commands that will do this for you.

Before finding the approximations to linear systems, it is important to remember that if A and B are both
matrices, then AB is not necessarily equal to BA. To distinguish the difference between solving systems
that have a right or left multiply, MATLAB uses two different operators,"/" and "\".

Examples of their use are given below. It is left as an exercise for you to figure out which one is doing
what.

>> v = [1 3 5]'
v =
1
3
5

>> x = A\v
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 3.469447e-018.

x =
1.0e+15 *

1.8014
-3.6029
1.8014

>> x = B\v
x =
2
1
-1

>> B * x
ans =
1
3
5

>> x1 = v'/B
x1 =
4.0000 -3.0000 1.0000

>> x1*B
ans =
1.0000 3.0000 5.0000

You might also like