Stage 2 .id
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 MATLAB’s “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 pmf’s.
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:
for variable = vector
statements
end
where the loop is iterated once for every value in vector. The general form of the if-statement is
if relation
statements
end
MATLAB’s rational operators are
< less than
> greater than
= 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 = [];
>> for n=1:3
v = [v n]
end
v =
1
v =
1 2
v =
1 2 3
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 = []; for n=1:3, v = [v n]; end
However, don’t use this way in practice! Because of MATLAB’s 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 tic and toc.
>> vec1 = [1:10e3];
>> for n=1:10e3, vec2(n) = n; end
>> vec3 = []; for n=1:10e3, vec3 = [vec3 n]; 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:
>> for m=1:2
for n=1:2
B(m,n) = (m+n)ˆ2;
end
end
>> B
B =
4 9
9 16
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
>> 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 > status
Again, the brackets are optional. We could also have written:
>> status = ((number > 0) & (number > help script.m
script file for plotting a function and its absolute value in two
subplots. The input data is stored in the variable func.
Function files
Function files enable the definition of new functions in MATLAB. Function files have the same
status in MATLAB as MATLAB’s 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.
function y = rand_int(m,n,range);
% rand_int Randomly generated integer matrix.
% rand_int(m,n) returns an m-by-n such matrix whos
% entries are between 0 and 9.
% rand_int(m,n,range) returns an m-by-n such matrix whos
% entries are between 0 and range.
% check usage
error(nargchk(2,3,nargin));
if (nargin < 3),
range = 9;
end
% generate random integer matrix
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 help function. This applies also to comments between statements.
Tell the reader in simple words what exactly takes place in the code.
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 MATLAB’s built-in function
for sorting out data in ascending order (see lookfor sort).
function [res,index] = sort_desc(data);
% sort_desc Sort in descending order.
% res = sort_desc(data) sorts the elements of the vector
% data in descending order. [res,index] = sort(data) also
% returns an index vector index, i.e., res = data(index).
% When data is complex, the elements are sorted by
% abs(data).
% check usage
error(nargchk(1,1,nargin));
% sort data in ascending order using the MATLAB built-in
% function sort
[res,index] = sort(data);
% reorder the data
[m,n] = size(data);
if (m ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.