You are on page 1of 10

Stage 1

MATLAB Self-do-tutorial (Part 1)


Contents
1.1 Introduction
1.2 Matrices
1.3 Matrix operations and functions
1.4 Graphics

1.1 Introduction
MATLAB is a technical software environment based on matrix manipulations offering both numerical
processing and visualization tools. MATLAB combines numerical analysis, matrix-computation, signal
processing and visualization tools with a simple user-friendly environment. Problems and solutions are
expressed using statements, which resemble standard mathematical expressions without the need for
developing software using traditional programming techniques such as C, Pascal or Fortran.
The goal of the self-do-tutorial is offering the student with some basic MATLAB knowledge
enough for a successful completion of the practices of this course. This means that simplicity has
priority over fast execution. Fantasy over creativity.
Attainment targets
The goals of the Self-do-tutorial are to be able:
to generate and manipulate matrices with MATLAB,
to visualize results in MATLAB,
to write MATLAB m-files.
Organization of this chapter
The MATLAB introduction is divided into five subsections. Matrices and matrix-functions are
discussed in the sections 1.2 and 1.3. A detailed description of MATLABs graphical visualization
tools is given in Section 1.4

1.2 Matrices
MATLAB works with a single object, an matrix, possibly including complex elements. Scalars are
treated as matrices, column vectors as matrices and row vectors as matrices. In this section, we shall
describe in details how to work with matrices, how to write/read variables and how to select
submatrices.
__

___

_ __

Generating matrices
To declare the (row) vector with, for example, elements 1, 3 and 4, we can type the following:
_

>>a=[134]
a=
134

Another way to declare vectors is to use an arbitrary increment between its elements, for example:
>>b=[0:2:6]
b=
0246

1
MATLAB

or simply:
>>b=0:2:6
b=
0246

This results in an integer vector with an increment of 2 between successive elements. The default
increment size (if not explicitly given) is 1. The transpose of a matrix or a vector is given by the
operation , that is,
>>a
ans=
1
3
4

results in the transposed of the vector . Special attention should be given to the fact that the MATLAB
operation transposes and complex-conjugates matrices. For transposition only, use the command
.. The last result of any operation that is not saved in a specific variable is kept by MATLAB in the
special variable ans.
It is possible to generate a column vector by separating the different rows using the semicolon,
i.e.,
_

>>[1;3;4]
ans=
1
3
4

Of course we can also define vectors with complex elements, using either or as the imaginary unit. For
example:
_

>>c=[2+i;i]
c=
2.0000+1.0000i
01.0000i

but also
>>c=[2jj]
c=
2.0000+1.0000i
01.0000i

Note that the operation not only transposes the vector, but also complex conjugates it. Additionally,
one can define a new imaginary unit, for example imunit=sqrt(1).
A matrix is defined in the same way as a vector. This is done by defining either a row vector of
columns, or a column consisting of rows, where the different rows are separated by a semicolon, e.g.,
>>A=[[147][258][369]]
A=
123
456
789

2
MATLAB in ET3502 Stochastic Processes 2004/2005

or
>>A=[123;456;789]
A=
123
456
789

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

Note that MATLAB is case sensitive (a A) and that terminating the command line with a semicolon
suppresses the display of its result. This feature will become essential when we want to display the
final result of complex computations, not being interested in intermediate results. MATLAB includes
many built-in functions for automatic matrix creation. Among these are:
zeros(matrix with zeros),
ones(matrix with ones),
eye(identity matrix).
__

Submatrices
MATLAB allows the selection of specific parts of a vector. For instance, to view only the first
three elements of the vector , we can type:
_

>>b(1:3)
ans=
024

To view the first and third element, type:


>>b([13])
ans=
04

If we wish to select all the elements beginning at a given position till (and including) the last
element, we can use the variable end:
>>b(2:end)
ans=
246

Note that the first vector element in MATLAB is indexed 1, and not 0. So,
>>b(0)
???Indexexceedsmatrixdimensions.

This is one of the most common error messages an unexperienced MATLAB user will encounter. Just
like vectors, we can select matrix elements, for example the element (1,2) of matrix :
_

>>A(1,2)
ans=
2

or the first two columns

3
MATLAB

>>A(1:3,1:2)
ans=
12
45
78

The same result can be achieved by typing:


>>A(:,1:2)
ans=
12
45
78

Here, the colon means all elements. To select the entire matrix, we thus type:
>>A(:,:)
A=
123
456
789

Variables
We can get the list of all currently defined variables using the commands whoand whos:
>>who
Yourvariablesare:
A
a
ans b

>>whos
Name Size
Bytes
Class
A
3x3
72
doublearray
a
1x3
24
doublearray
ans 3x2
48
doublearray
b
1x4
32
doublearray
c
2x1
32
doublearray(complex)
Grandtotalis24elementsusing208bytes

To view the dimension of a specific variable, use the sizecommand, for example:
>>size(b)
ans=
14

It is often sufficient to know only the length of a vector. To do so, use the command length:
>>length(b)
ans=
4

The clearcommand clears variables:


>>clearc
>>who
Yourvariablesare:
A
a
ans b

4
MATLAB in ET3502 Stochastic Processes 2004/2005

When exiting a MATLAB session, all variables are destroyed. However, with the command save
it is possible to save all declared variables to the file matlab.mat before exiting the session. Later,
when starting a new session, one can read these saved variables by typing load. Its also possible to
save only specific variables. For example to save the matrix to a file named A matrix.mat type:
_

>>saveA_matrixA

This file can be read later with the command:


>>loadA_matrix

If you wish to write data in an ASCII format, use the option ascii. Use the helpfunction to view
other available options of save(helpsave).
We can format an output file with the use of the commands fopen,fprintfand fclose
(see the helpinformation of these commands). Writing the vector to a file a vector.data using 6
digit notation of which three following the decimal point, we can type:
_

>>fp=fopen(a_vector.data,w);
>>fprintf(fp,%6.3f%6.3f%6.3f n,a(1),a(2),a(3));
>>fclose(fp);
_

If fp=1(default value), the output will be sent to the standard output (the monitor).

1.3 Matrix operations and functions


In this section, we explore different matrix manipulation techniques.
Matrix operations
As you might have noticed by now, MATLAB uses the standard linear-algebra notation. Both linear
and non-linear operations, like addition, subtraction, multiplying, and raising to a power ( +,,*and
^, respectively) can be easily achieved. Pay attention to matrix and vector dimensions.
See the following examples:
>>A*a
???Errorusing==>*Innermatrixdimensionsmustagree.
>>A*a
ans=
194367
>>b(2:4)*A
ans=
607284
>>a+b([124])
ans=
1510

It is sometimes desirable to perform element-wise operations. This is done by placing a point before
the mathematical symbol. For example, to raise each element of matrix to the power of two, we type:
_

>>A.2
ans=
149
162536

5
MATLAB

496481

This is not equivalent to


>>A2
ans=
303642
668196
102126150

indicating the matrix product


Matrix functions
MATLAB has many built-in functions. Some (e.g. sin) work on scalars. When called with a matrix
argument, those functions will work on each element separately:
>>sin(b)
ans=
0
0.9093
>>max(sin(b))
ans=
0.9093

0.7568

0.2794

In perspective of random variables and stochastic processes functions will be often work on random
outcomes of experiments. On generating random numbers simulating outcomes and on analyzing
outcomes of experiments. In the following we use the function rand,which generates from a pseudo
random number generator a number in the interval (0,1). Each time you use rand your specific
answer will be different from ours but must have the same properties:
>>rand
ans=
0.0153
>>rand
ans=
0.7468
>>rand
ans=
0.4451

Till now the outcome is shown as the ans. If the value of rand e.g. is compared to a scalar:
>>rand>0.5
ans=
1
>>rand>0.5
ans=
0

only the result is presented and we cant check the quality of the code. This is typical in stochastic
environments. If not desired, first a variable can be introduced that holds the generated random
number(s):
>>y=rand
y=
0.4186
>>y>0.5

6
MATLAB in ET3502 Stochastic Processes 2004/2005

ans=
0

Other MATLAB functions work on vectors, but column-wise when called with matrix arguments.
An example is the function max, which returns the largest element of a vector:
>>rand(1)
ans=
0.8381
>>rand(1,4)
ans=
0.95010.23110.60680.4860
>>rand(1,4)
ans=
0.89130.76210.45650.0185
>>max(rand(1,4))
ans=
0.8214
>>X=rand(1,6)
X=
0.92180.73820.17630.40570.93550.9169
>>max(x)
???Undefinedfunctionorvariable'x'.
>>max(X)
ans=
0.9355
>>Y=rand(3,4)
Y=
0.41030.35290.13890.6038
0.89360.81320.20280.2722
0.05790.00990.19870.1988
>>max(Y)
ans=
0.89360.81320.20280.6038
>>max(Y')
ans=
0.60380.89360.1988
>>max(max(Y'))
ans=
0.8936

The most powerful functions in MATLAB are the matrix functions. Examples of such functions
are invwhich returns the inverse of a matrix, and eig, which returns the eigenvalues and
eigenvectors of a matrix. To find out the right way a function should be used, you can use the help
command:
>>helpeig

7
MATLAB

EIG

Eigenvaluesandeigenvectors.
E=EIG(X)isavectorcontainingtheeigenvaluesofasquare
matrixX.
[V,D]=EIG(X)producesadiagonalmatrixDofeigenvaluesand
afullmatrixVwhosecolumnsarethecorresponding
eigenvectorssothatX*V=V*D.
[V,D]=EIG(X,nobalance)performsthecomputationwith
balancingdisabled,whichsometimesgivesmoreaccurateresults
forcertainproblemswithunusualscaling.
E=EIG(A,B)isavectorcontainingthegeneralizedeigenvalues
ofsquarematricesAandB.
[V,D]=EIG(A,B)producesadiagonalmatrixDofgeneralized
eigenvaluesandafullmatrixVwhosecolumnsarethe
correspondingeigenvectorssothatA*V=B*V*D.
SeealsoCONDEIG.

Overloadedmethods
helplti/eig.m

So, if we want to compute the eigenvalue decomposition , we can type the following:
>>[SLambda]=eig(A);

To check that we made no errors, we can execute the following calculation:


>>S*Lambda*inv(S)
ans=
1.0000
2.0000
4.0000
5.0000
7.0000
8.0000

3.0000
6.0000
9.0000

Due to internal number rounding, the result equals to the matrix only up to a limited accuracy. In this
example we have
_

>>Aans
ans=
1.0e014*
0.0777
0.2665
0.3553

0.3109
0.0888
0.0888

0.3997
0
0.3553

Take care when comparing computed results. A test such as


>>x==0

can return a 0 (false), while


>abs(x)<1e15

can return 1 (true). Rational operators are discussed extensively in Part 2 of this tutorial.

8
MATLAB in ET3502 Stochastic Processes 2004/2005

MATLABs output format can be adjusted with the command format(see helpformat).
If we want to use, for example, a five digit floating-point representation, we type:
>>formatshorte
>>ans
ans=
7.7716e16
2.6645e15
3.5527e15

3.1086e15
8.8818e16
8.8818e16

3.9968e15
0
3.5527e15

It is also possible to suppress blank lines in the standard output.


To use a mathematical function without knowing its name in MATLAB, we can use the command
lookfor. This function searches all m-file help entries for a given string. How such m-files exactly
look like will be discussed in detail in Part 3 of this tutorial. Assume we want to generate random
numbers. To find the corresponding MATLAB function, we can type:
>>lookfor'randomnumbers'
RANDUniformlydistributedrandomnumbers.
RANDNNormallydistributedrandomnumbers.
RANDOMGeneratesrandomnumbersfromanameddistribution.

and we can choose the one that specifically serves our purposes. Note that if the string contains more
than one word we must put quotes (.....) around the string. For an overview of the most important
MATLAB functions commands and variables see [1, pp. 22-35].

1.4 Graphics
For the visualization of data we can open a graphical window. The command figureopens such a
window and returns a, for each window unique, integer (a so-called handle), for example
>>h=figure
h=
1

Using get(h)we can view the object properties of the figure (like position, dimension, etc.).
There are many ways to visualize data. The ones most used are plotfor plotting two dimensional
data, and surfand meshfor three dimensional plots. See the available help information using the
helpcommand. To plot, for example, a number of uniformly distributed outcomes, we can type:
>>n=1:100;
>>X=rand(1,100);
>>plot(n,X);

Furthermore, we can adjust the plotting range and add a grid.


>>axis([02000.11.1]);
>>grid;
inoctaveusecommand
>>gsetgrid;

Several ways exist for plotting multiple functions at the same time with different colors and line

9
MATLAB

types. We can do this with only one plot statement


>>plot(n,X,r,n,X>0.5,b);
>>axis([02000.11.1]);

or separately using the command hold:


>>Y=(X>0.5);
>>plot(X);
>>axis([01000.11.1]);
>>holdon
>>plot(Y,r);
>>Z=Y.*X;
>>plot(Z,g);

In addition, you can generate two plots in different subplots in one figure (above or next to each
other). To do this, use the command subplot. See the following example.
>>subplot(3,1,1);
>>plot(X);
>>axis([01000.11.1]);
>>subplot(3,1,2);
>>plot(Y);
>>axis([01000.11.1]);
>>subplot(3,1,3);
>>plot(Z);
>>axis([01000.11.1]);

If desired, the colors of the subplots can be changed, so can the solid-line presentations. Such a
plotting could be:
>>subplot(3,1,1);
>>plot(X,'bo');
>>axis([01000.11.1]);
>>subplot(3,1,2);
>>plot(Y,'r+');
>>axis([01000.11.1]);
>>subplot(3,1,3);
>>plot(Z,'gd');
>>axis([01000.11.1]);

10
MATLAB in ET3502 Stochastic Processes 2004/2005

You might also like