Sei sulla pagina 1di 8

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

MATLAB also has other windows including the Figure Window to display graphs and the
Editing Window see in the figure below.

MATLAB Tutorial

Tutorial 1
INTRODUCTION
MATLAB is a an interpreted mathematical language and computational tool whose name is
short for Matrix Laboratory. Interpreted languages (i.e. MATLAB, LISP etc.) are usually much
easier to use, but are not as numerically efficient as compiled languages (i.e. FORTRAN, C,
Pascal etc.). Given the origin of MATLABs name its default mode for arithmetic operations is in
matrix notation. Special syntax is sometimes required to force MATLAB to interpret things
like a scalar like most computational tools. MATLAB allows for the simple calculation of
many mathematical problems and it also contains typical programming structures to allow the
writing of programs. MATLAB does numerical calculations, as well as symbolic calculations
similar to MAPLE and MATHEMATICA but through the use of a special toolbox.
MATLAB is a registered trademark of The MathWorks Inc.
As see in the figure below MATLAB version 7 has various window sections

BASIC OPERATIONS
Upon starting MATLAB you may see various messages regarding the loading of various
toolboxes. Once this is completed you will see the MATLAB prompt (which looks like a double
greater than sign >> ). You may type basic variable assignments and mathematical operations at
the prompt in a fashion similar to various calculator interfaces and other mathematical tools like
MAPLE of MATHEMATICA. Typing the RETURN key will carry out the calculation.
Workspace gives
information on
current variables

First MATLAB can be used like a basic calculator:


Exercise 1:
>> 3/2
ans =

Command window
shows commands
and results

1.5000
>>

3^2

ans =
9
>>

2*pi

ans =
6.2832
>>

Command history

(3*4+7)/(6+11)/2 + 3^1.3

ans =
4.7300

The standard operators in MATLAB work for both matrices and scalars.
ZK Nagy

ZK Nagy

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

Exercise 3:

Basic Operations
Operation
symbol
addition
+
subtraction
multiplication
*
division
/
to the power of
^

>>

2*pi

ans =
6.2832
>> pi=1
pi =
1

Note that the calculation is always returned in the default variable ans which is the answer
to the last calculation done. Values can also be assigned to variable names with the equal
sign, and these variables may also be used in calculations as seen in the examples below

>> 2*pi
ans =
2

Exercise 2
>> DOUBLEPI = 6.2832

If you wish to put things back to their default assignments simply clear your variables with the
clear command which is explained below under MATLAB ADMINISTRATION. Some other
special variables and functions are given in the tables below.

DOUBLEPI =
6.2832
>>

var1=4

var1 =

Variable
ans
pi
computer
i or j
inf
eps
NaN

4
>> var2=9.2
var2 =
9.2000
>> var3=var2+var1
var3 =

Special Variables
variable value
most recent answer

current computer type


square root of -1
infinity
floating point relative accuracy
Not a number (used for error output)

13.2000

Some Useful Mathematical Functions


function
exponentiation (e^)
exp
abs
absolute value
cos, sin, tan
cosine, sine and tangent
acos,asin,atan
inverse of cosine, sine and tangent
cosh,sinh,tanh
hyperbolic functions (also inverses)
sqrt
square root
conj
complex conjugate
fix
round toward zero
round
round toward nearest integer
log
natural logarithm
log10
base 10 logarithm
real
real part of complex number
imag
imaginary part of complex number

>> var1=DOUBLEPI/2

symbol

var1 =
3.1416

Please be careful of what variable names you choose because MATLAB will overwrite its own
variables and functions. Since MATLAB is case sensitive you can avoid this by using capital
letters for your functions and variables because most of MATLABs built in functions are in
lowercase (just the opposite of MATHEMATICA). For example you can overwrite pi as seen
below:

ZK Nagy

ZK Nagy

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

USING VECTORS & MATRIXES


The real power of MATLAB is its ability to deal seamlessly with matrices. Matlab is a powerful
tool to manipulate arrays, vectors, and matrices. For example in C or FORTRAN77 the command
to multiply two matrices would contain many lines of code and a "for" loop. In Matlab, the
command to multiply two matrices A (for example a 23 matrix) and B (a 32 matrix) is simply
A*B. The basic operators you saw above work for matrices and vectors as well as seen in the
example below. The basic operators you saw above work for matrices and vectors as well as seen
in the example below.

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

Note that the individual elements of a vector or matrix are assembled between square brackets
and may be separated by spaces or by commas as seen above. To assemble a matrix you may use
a semicolon to separate individual rows as seen below.
Exercise 5
>> A=[1 1 1; 1 2 3; 2 -2 1]
A =
1 1 1
1 2 3

Exercise 4

2 -2 1
>> a=[1 2 3]
a =

Matrices can also be assembled using colons which work like loops. The syntax is:
MATRIX=[start:increment:finish] where MATRIX above is a vector containing a
sequence of values starting from start and counting up the finish with a step size of
increment as seen in the example below. Note that if the increment value is omitted an
increment of 1 is assumed.

1 2 3
>> b=a'
b =
1

Exercise 6

>> a=[1:1:3]

a =
>> a*b
1

ans =
>> b=[1:3]

14

b =

The example above illustrates the assembly of a row and column vector which are then
multiplied together. This example introduces the transpose operator which is an apostrophe
(). The transpose operator simply interchanges the rows and columns of a matrix. It is easy to
type matrices into MATLAB as rows, and the transpose operator will help you align data as
columns. Please note that MATLAB adheres to the standard rules of matrix algebra and will
not let you violate them by multiplying a row vector by a row vector as see below.
>> a=[1 2 3]
a =

>> c=[10:-2:0]
c =
10

>> b=a
b =
1 2 3
>> a*b
??? Error using ==> *
Inner matrix dimensions must agree.

There are many special functions used to quickly assemble matrices some of these are listed in
the table below.
Function
eye
zeros
ones
rand
randn
diag

1 2 3

Special Matrices
creates an identity matrix
creates a matrix or vector of all zeros
creates a matrix or vector of all ones
creates a matrix or vector filled with uniformly distributed random numbers
creates a matrix or vector filled with normally distributed random numbers
create or extract matrix diagonal

The syntax of each of these functions is discussed under their headings in the help command
(discussed below under MATLAB ADMINISTRATION).
ZK Nagy

ZK Nagy

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

Matrices can also be assembled from other matrices using commas or semicolons as seen below.
Exercise 7
>> a=ones(1,3)
a =
1
1
1
>> b=[1:3]
b =
1
2
>> c=[2 -2 1]
c =
2
-2
>> A=[a, b, c]
A =
1
1

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

Matrix manipulations can be carried out using the colon operator (:). When accessing parts of a
matrix the matrix name is followed by closed parentheses where the first index is the row and the
next index separated by comma is the column. In addition to the lists as seen above the colon by
itself refers to all rows or columns in a matrix. For example taking matrix A below we can make
various manipulations.
Exercise 9

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


>> A
A =

-2

1
5
9

2
6
10

3
7
11

4
8
12

13

14

15

16

>> A=[a; b; c]
A =

access the element in the 2nd row 3rd column of matrix A

1
1

1
2

1
3

>> A(2,3)

-2

ans =
7

Almost any function in MATLAB can be used on a matrix. For example, sin(A) would be a 22
matrix that has the value of sine of each element of A. Some important matrix functions are listed
in the table below:

access the 2nd row of matrix A


>>

A(2,:)

Matrix Functions
matrix calculation

ans =

function
inv
det
cond
eig
rank
expm

matrix inverse
matrix determinant
matrix condition number
eigenvalue-eigenvector calculation
matrix rank
martix exponential

access the 3rd column of matrix A

5 6 7 8

>>

A(:,3)

ans =
3
7
11
15

To learn more about matrix functions first type >> help and press Return. A list of basic
operators will scroll down the screen. For further information about matrix functions type >>
help matlab\elmat and >> help matlab\matfun or go to the html help and electronic book files.

access rows 1 through 3 of columns 3 and 4 of matrix A


>>

A(1:3,3:4)

ans =

Important functions the give information about the variables are, size (size of a matrix, vector)
and length (length of a vector)
Exercise 8

3
7
11

access row 1 of matrix A but reverse the order

Try the following commands:

>>

>> length(a)

ans =

A(1,4:-1:1)

4 3 2 1

>> size(A)
ZK Nagy

4
8
12

ZK Nagy

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

Exercise 10
Now lets illustrate some other matrix functions using a system of linear equations as an example.

Since our linear system is written as in the former of the two examples we can use the
backward slash.

x1 + x2 + x3 = 6
x + 2x +3x = 14
1
2
3
2x1 2x2 + x3 = 1

>> A
A =

which can be written in matrix notation as:


1 1 1
x1
Ax = b
where A = 1 2 3 x = x 2
2 2 1
x3

1 1 1
1 2 3
2 -2 1

6
b = 14
1

>> b

x = A 1b

b =
6
14
1

Lets solve this at the Matlab prompt:

>> x=A\b

>> b=[6 14 1]'

x =
1
2
3

We have already seen how to assemble the


column vectors like b above. It is done with
the transpose operator as seen here.
You can verify the result by

b =

6
14
1

Exercise 11
By default MATLAB does math in matrix notation, to change to element by element place a
period in front of the operator. For example a^2 will carryout a*a while a.^2 will square every
element of matrix a.

>> A=[1 1 1; 1 2 3; 2 -2 1]
A =
1
1
2

1
2
-2

Define the A matrix

3
1

>> x=inv(A)*b
x =

We know that the linear system of equations above can


be solved by multiplying the vector of right hand side
values (b) by the inverse of the coefficient matrix (A).

1.0000
2.0000
3.0000

ans =
6.0000
14.0000
1.0000

>>

a=[1 2 3];

>>

b=[2 5 8];

>>

a*b

Define these two vectors. Note that the semicolon


(;) after suppresses their value being shown.
Suppose we try to multiply them.

??? Error using ==> *


Inner matrix dimensions must agree.

You can verify the result by

>> A*x

>>

This is exactly the b vector

What happened? The multiplication symbol


by itself when applied to vectors or matrices
is interpreted to mean matrix multiply.

a*b'

ans =
36

The correct way to do is by transposing the second vector


This gave (1*2 + 2*5 + 3*8) = 36, the usual scalar product of two vectors.

>>

Note that in the above example simply by typing a variable its contents are displayed. It is not
necessary to take the inverse of a coefficient matrix to find its solution. A simple application of
Gauss-Jordan elimination on the augmented matrix is more efficient that taking the matrix
inverse. MATLAB uses the metaphor of dividing by the coefficient matrix (as one would do in
a scalar equation) to solve this. The following syntax is used to solve a linear system depending
on how it is written.
for Ax = b use the backward slash:

x = A\b

for xA = b use the forward slash:

x = b/A

ZK Nagy

By writing the variable name to the prompter and


pressing the <return> will show its value

a.*b

ans =
2 10 24

>>

a.^2

ans =
1 4 9

ZK Nagy

If we want the element by element product, we must put a period before the
multiplication symbol:

The same procedure must be followed in doing division and


exponentiation. For example, if you want the square of each element in a
vector you must use.

10

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

MATLAB ADMINISTRATION

Exercises for self study

There are a number of commands that allow you to control the MATLAB environment. Some
of these are listed in the table below.

Individual Exercise 1

For matrices A and B defined below, type the following commands and observe the results:
>> A=[5 6 7;10 4 6;2 8 10] <return>

command
help
whos
who
clear
clc
what
lookfor

>> B=[1 3 0;5 13 5;8 2 1] <return>


>> A+B

>> A Transpose of A

>> A^2

>> A*B

>> A^(-1)

>> A*A

>> A./5
>> A/A

>> B*A

>> inv(A) Inverse of A

>> A.^2

>> A/B

>> 5*A

>> A-B

Managing Commands, Functions, Variables and Workspace


function
invokes the on-line manual pages in MATLAB
list current variables with memory size
list current variables
clear current variables and functions from memory
clear command window
directory listing of M files
keyword search through help pages

Individual Exercise 2

1. Define a 33 identity matrix I by using the appropriate function.


2. Define the following matrices:
A = [1 2 3;7 8 9;13 14 15] and B = [4 5 6;10 11 12;16 17 18]

3. Create the row vector C from A and B that is equal to C=[1 2 3 4 .... 18]. Hint: Start with
C=A(?,?) then let C=[C B(?,?)] then C=[C A(?,?)],. Follow this pattern until you obtain the
desired C. You fill in the correct values for "?".
4. What would be a really easy way to create the vector C without even using matrices A and
B.

Command
cd
delete
dir

Functions that Interface with the Operating System


Function
change current directory; show current directory
delete file
directory listing

The first and most important command of this type is the help command because it allows
access to information on all other commands. Typing help shows all the categories of help as
seen below. For more help on directory/topic, type "help topic". Alternatively, typing of help
followed by a specific topic or function gives the details.
>> help clear

5. Create a 4001 column vector of ones. Hint: Do not type [1;1;1;1;1;1;1...........]


6. Given matrix A from Part 2 find the mean values of the columns and rows using the mean
function. Hint: Use help to learn how to use mean, and remember the transpose of a matrix.

Of the remaining functions in the table above the second most important one is the whos
command. It shows the details of the currently defined variables as seen in the workspace.

7. Using A and B from Part 2 and D=[A B] determine which ones of the following will work:
a) A*D

e) A*D

i) A/D

b) D*A

f) A*D*B

j) D/A

c) A*B

g) A*B*D

k) D(:,(1:3))*A

d) D*A

h) A/B

l) D((1:3),:)*A

Hints:
- A useful property of the command line editor is that by using the cursor (arrow) keys you
may backtrack through previous commands and then edit them before executing them again
by hitting the return key. This is useful for complex commands, when you make typing
errors or want to repeat (and change) a previous command. The up and down arrows will step
through all the commands given since the MATLAB sessions was started. You can also use
the command history window to search and execute previous commands.

Individual Exercise 3
-

If you looking for a special command and you remember the first letter(s) the search is made
easier by typing those characters before using the arrow keys.

Several commands may be given on the same line in MATLAB. The commands are
separated by commas or by semicolon (to avoid display)

Solve the following system of linear equations:


5x1 + 3x2 - x3 = 5
2x1 - 7x2 - 3x3 = 0
x1 + 5x2 + 6x3 = -7
ZK Nagy

11

ZK Nagy

12

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

COMPLEX NUMBERS

PLOTTING

MATLAB works with complex numbers! Use i or j in the definition of the numbers. Note try to
avoid using i or j as variable names.

Numerous plotting capabilities exist in MATLAB; some of the useful commands are given in the
table below

Exercise 12
Introduce the following commands to the Matlab prompt

2D

>> z1 = 1+3*i
z1 =

3D

1.0000 + 3.0000i
>> z1 + 2*i

Define a complex number using i or j


ans =

Generic

1.0000 + 5.0000i
>> z1^2
ans =
-8.0000 + 6.0000i
>> z2=3*j
z2 =

Plot commands
Command
Function
plot
linear plot 2-D points or lines
loglog
log-log plot 2-D points or lines
semilogx, semilogy semi-log plot 2-D points or lines
bar
plot 2-D bar graph
hist
plot histogram
plot3
plot 3-D points or lines
mesh
Plot 3-D mesh grid
surf
Plot 3-D surface plot
title
add title to graph
axis
modify axis scaling or appearance
xlabel, ylabel
add x or y axis label
hold on/off
holds the current plot
text
add text annotation
divides figure window
subplot
open new figure window
figure
adds the grid lines
grid
graph legend
legend

The table above contains only a small number of the MATLAB plotting commands, typing
help graph2d, help graph3d, and help
graphics for more information on MATLAB
plotting. The following example illustrates a simple
xy graph.

0 + 3.0000i
>> z2^2
ans =

Exercise 13

-9

>>
>>
>>
>>
>>
>>
>>
>>

>> sqrt(-4)
ans =
0 + 2.0000i

Multiply a complex number with is


conjugate conj

t=[0:0.01:10];
p1=cos(t);
p2=sin(t);
p3=p1.*p2;
plot(t,p1,t,p2,t,p3)
title('Example Plot')
xlabel('t (seconds)')
legend('cos', 'sin', 'cos(t)*sin(t)')

>> z1*conj(z1)

The above example will produce the first plot displayed above in the current plot window. Please
note that on the screen this plot will show up with each line plotted in a different default color.
However, these plots cant be copied into a report easily unless you have access to a color printer.
In order the make this plot easier to copy into a black and white report simply include an
additional field in the plot command for each curve to be graphed. These fields in quotes are
explained under the help utility for the plot. Write >> help plot to see the options of this
command.

ans =
10

ZK Nagy

13

ZK Nagy

14

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

In the 2nd plot below we have also added a title and a y axis label as well as plotting all the lines
in black with various types of lines. We also illustrate how to ad points to existing plots and plot
grid lines.
Exercise 14

CGB014/CGB006 Instrumentation, Control and Industrial Practice

Matlab Tutorial

You can copy your figure in your report in (e.g. in


Word) by using from the menu the Edit -> Copy
Figure options and then from the Edit menu of
Word the Paste option.

Execute the following commands one by one


and observe the result
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>

figure
t=[0:0.01:10];
p1=cos(t);
p2=sin(t);
p3=p1.*p2;
plot(t,p1,'k--',t,p2,'k-',t,p3,'k:')
xlabel('t (seconds)');
ylabel('f(t)');
title('Example Plot 2')
legend('cos', 'sin', 'cos(t)*sin(t)')

>>
>>
>>
>>
>>
>>

t2 = [0:0.2:10];
p4= cos(t2);
hold on
plot(t2,p4,'kx')
hold off
grid

MATLAB is very powerful I generating 3D figures.

Exercise 15

We want to represent the surface given by the equation z = xy(x2-y2)/(x2+y2) on the interval [-3 3]
for both x and y.
linspace(a,b,N) generates N linearly
distributed values between a and b
Enter the following commands
>> x = linspace(-3,3,300);

and
You can edit the properties of the figure from the object editor, by using the edit tool
double clicking on the particular part of the figure. Example to make one of the lines thicker you
may follow the procedure below:

>> y = x;

[X,Y] = MESHGRID(x,y) transforms the domain specified


by vectors x and y into arrays X and Y that can be used for the
evaluation of functions of two variables and 3-D surface plots.

>> [X, Y] = meshgrid(x,y);

1. Select
edit tool

>> Z = X .* Y .* (X.^2 - Y.^2)./(X.^2 + Y.^2);


>> mesh(X,Y,Z)

Use the .* and .^ operators to calculate


the expression element by element.

2. Double
click on line

3. Increase
line thickness

ZK Nagy

15

ZK Nagy

16

Potrebbero piacerti anche