Vous êtes sur la page 1sur 5

Stage 2

MATLAB Self-do-tutorial (Part 2)


Contents
2.1 Control statements
2.2 M-files

Attainment targets
The goals of the Self-do-tutorial are to be able:
to generate and manipulate discrete random variables.
Organization of this chapter
Section 2.1 describes the use of MATLABs for and if constructions, as well as relational and
logical operators. Section 2.2. discusses working with m-files. These files are used for writing
MATLAB script files or for defining new MATLAB functions. Section 2.3. deals with generating
samples of discrete random variables and pmfs.

2.1 Control statements


In this section we study how to use the for, if and relational operators in MATLAB. These
principally work in the same way as control statements do in most computer languages, particularly
as in C. The for-loop has the folowing general form:
forvariable = vector

statements
end

where the loop is iterated once for every value in vector. The general form of the if-statement is
ifrelation

statements
end

MATLABs rational operators are

<
>
<=
>=
==
~=

less than
greater than
less than or equal to
greater than or equal to
equal to
not equal to

Here are some examples:


For-loop
The following commands generate a row vector with elements 1, 2 en 3 using a for-loop:
>>v=[];
>>forn=1:3
v=[vn]

1
MATLAB in ET3502 Stochastic Processes 2004/2005

end
v=
1
v=
12
v=
123

Note that the use of an empty matrix is allowed ( v=[]). We can also write these commands in
one line. To do this, we separate commands by a semicolon if the display of their result should be
suppressed or a comma if we want to display the intermediate result. So, if we are not interested
in intermediate results, we type:
>>v=[];forn=1:3,v=[vn];end

However, dont use this way in practice! Because of MATLABs interpreting nature, each line is
interpreted independently resulting in the allocation of new memory for vector at each iteration.
This significantly lowers performance speed. Compare the three following commands, all giving
the same results: To measure the elapssed time, use the commands ticand toc.
_

>>vec1=[1:10e3];
>>forn=1:10e3,vec2(n)=n;end
>>vec3=[];forn=1:10e3,vec3=[vec3n];end

It is clear that, whenever possible, one should avoid the use of loops. Always try to vectorize your
data!
The same methods can, of course, be used for matrix generation. For example:
>>form=1:2
forn=1:2
B(m,n)=(m+n)2;
end
end
>>B
B=
49
916

If-statements
The next example, demonstrating the use of if-statements, determines if a random number is negative
((sign=1), positive ((sign=1), or equal to zero ((sign=0):
>>number=randn;
>>if(number<0),
sign=1;
elseif(number>0),
sign=1;
else
sign=0;
end

2
MATLAB in ET3502 Stochastic Processes 2004/2005

>>sign

The brackets around the relations in the if-statements are not compulsory. In many cases, however,
it does enhance code readability.
Relations can be combined with the Boolean array-operators en (logical and, or and
not, respectively). For example, if we wish to determine whether a random number lies within the
interval (0,], we type:
__ _

>>number=randn;
>>if((number>0)&(number<=0.5)),
status=1;
else
status=0;
end
>>status

Again, the brackets are optional. We could also have written:


>>status=((number>0)&(number<=0.5))

In addition to the for and if-statements, MATLAB offers the common while and case statements.
Check their syntax using the help-function.

2.2 M-files
MATLAB can execute statements from a text file. These files (called m-files) must have the file
extension .m. There are two types of m-files: script files and function files.
Script files
A script file contains a series of MATLAB statements. All variables within that file are global
and will conflict with variables having the same name in the current MATLAB session. As an
example, lets assume that we want to plot a given function as well as its absolute value, on top of
each other, using subplots. The script file will take the following form:
%scriptfileforplottingafunctionanditsabsolutevalueintwo
%subplots.Theinputdataisstoredinthevariablefunc.
%checkiffuncexists
if(exist(func)=1),
error(Thevariablefuncdoesnotexist);
end
%openafigureandplotthefunctionintheuppersubplot
figure;
subplot(2,1,1);
plot(func);
set(gca,fontsize,8);
xlabel(x);
ylabel(f(x));
%plottheabsolutevalueofthefunctioninthebottomsubplot
subplot(2,1,2);

3
MATLAB in ET3502 Stochastic Processes 2004/2005

plot(abs(func));
set(gca,fontsize,8);
xlabel(x);
ylabel(|f(x)|);

The function existdetermines whether variables or functions with a given name are defined.
The function errordisplays an error message and stops the execution of an m-file. The %symbol
indicates that MATLAB should treat all text from this symbol to the end of that line as a comment
(and ignore it). The first comment lines (until the first non-remark line) are used by the help
function. That applies to every m-file, whether those comments are at the beginning, or at the end
of the file. Thus,
>>helpscript.m
scriptfileforplottingafunctionanditsabsolutevalueintwo
subplots.Theinputdataisstoredinthevariablefunc.

Function files
Function files enable the definition of new functions in MATLAB. Function files have the same
status in MATLAB as MATLABs internal function. Variables inside a function file are local by
default. However, one can define global variables with the command global. We demonstrate
the use of a function file with a simple example, which generates a matrix of random integers.
functiony=rand_int(m,n,range);
%rand_int
%
%
%
%

Randomlygeneratedintegermatrix.
rand_int(m,n)returnsanmbynsuchmatrixwhos
entriesarebetween0and9.
rand_int(m,n,range)returnsanmbynsuchmatrixwhos
entriesarebetween0andrange.

%checkusage
error(nargchk(2,3,nargin));
if(nargin<3),
range=9;
end
%generaterandomintegermatrix
y=floor((range+1)*rand(m,n));

The first line declares the function name (rand_int), together with input and output arguments
(m,n,range) and (y). Without this line, the file would be an ordinary script file.
It is advisable, as is done in the above example, to make use of the built-in MATLAB functions
error, nargchk(check number of arguments) and nargin(number of input arguments). Using
these functions, MATLAB will generate an error message if the function is being called with the
wrong number of arguments. This is very helpfull when nested function calls are used (when a
function is called from within the body of another function). Try to follow these rules and comment
your code for the use of the helpfunction. This applies also to comments between statements.
Tell the reader in simple words what exactly takes place in the code.

4
MATLAB in ET3502 Stochastic Processes 2004/2005

We end this section with an example of a function file with two output arguments. This function
sorts out the elements of a vector in decreasing order. We use MATLABs built-in function
for sorting out data in ascending order (see lookforsort).
function[res,index]=sort_desc(data);
%sort_desc
%
%
%
%
%
%checkusage

Sortindescendingorder.
res=sort_desc(data)sortstheelementsofthevector
dataindescendingorder.[res,index]=sort(data)also
returnsanindexvectorindex,i.e.,res=data(index).
Whendataiscomplex,theelementsaresortedby
abs(data).

error(nargchk(1,1,nargin));
%sortdatainascendingorderusingtheMATLABbuiltin
%functionsort
[res,index]=sort(data);
%reorderthedata
[m,n]=size(data);
if(m<=n),
res=fliplr(res);
index=fliplr(index);
else
res=flipud(res);
index=flipud(index);
end

5
MATLAB in ET3502 Stochastic Processes 2004/2005

Vous aimerez peut-être aussi