Matlab Primer Part2 PDF
Matlab Primer Part2 PDF
1
A comprehensive treatment is given in Mastering Matlab, Hanselman and Littlefield, Prentice Hall. The
extensive Matlab documentation provided with the software is also very readable and informative .
2
This is not strictly true but sufficiently close to the truth that it will serve its purpose.
The simplest way of creating small arrays in Matlab is to manually enter the elements in
the command window, row by row. Try entering the commands given below:–
Comments
The enclosing square brackets indicate that the contents form an array. A semi-
colon within the brackets indicates the start of a new row.
We can turn a row vector into a column vector, by using the transpose operator
>>A' %Transpose A
All 2-D arrays must be rectangular or square – in other words, to be a legal array each
row in the array must have the same number of elements 3. The same principle applies to
arrays of higher dimension. Thus a legal 3-D array must comprise a “stack” of 2-D arrays
3
So-called cell arrays and structures are advanced data structures which can be used to circumvent this
restriction when needed. We must defer discussion of these data structures for later examples in the book
but for the impatient reader, typing >> doc struct and >> doc cell at the Matlab prompt for information on
the basic idea and use.
of similar dimensions, a legal 4-D array a group of 3-D arrays of similar dimensions and
so on.
We can change or correct the values of array elements by indexing them individually:–
Matlab has a very important and powerful colon operator ( : ). This can be used to create
vectors and for subscripting arrays. Here’s a couple of examples of its use in creating
vectors -
We can also access groups of elements in an array by using the colon operator to specify
the vector indices. Try the following :-
We can also use the colon operator to extract entire rows or columns of an array:-
When we use the colon operator along one of the array dimensions in this way, we are
effectively allowing the index to range over the entire length of that dimension. Thus in
the first example, A(:,1) means we fix the column number equal to 1 and extract all the
elements in that column (i.e. the row index varies from 1 up to its maximum value). In
the second example, A(2,:) we fix the row number equal to 2 and extract all the elements
in that row (i.e. the column index varies from 1 up to its maximum value).
Concatenation of arrays
We can easily concatenate (join together) arrays to make a larger array. In effect, we just
consider the elements of an array to be arrays themselves.
The arrays which form the elements of the concatenated array must be of conformable
dimension – i.e. the resulting array must be rectangular. For example, trying to form the
arrays :–
>> [A; C]
>> [A B C]
does not work and Matlab responds with the appropriate error message –
• Matlab provides a number of built in functions for creating and manipulating simple
arrays of arbitrary dimension. These are outlined in the table 2.1 below.
>>clear;
>>A=ones(128); surf(A); %Generate array of ones, display as surface height.
The last example uses the powerful in-built find function and so-called linear indexing.
We’ll discuss this function and the technique of linear indexing shortly, so don’t worry if
all the last example is not completely transparent.
Those with some previous programming experience will note from the examples above
that there are no loop constructs (for, do, while etc) used to build and manipulate the
arrays. A feature of Matlab which distinguishes it from many other languages is called
implicit vectorisation. Namely, if the input to a Matlab expression is a vector or array,
Matlab knows to evaluate the expression at every value of the input, producing an output
that is also a vector or array.
A second way in which larger arrays can be constructed is through use of appropriate
loop constructs. This is done in a way similar to most other languages. The following
example assigns the value 1 to all the elements in column 1, 2 to all the elements in
column 2 and so on :–
The next example creates an array that randomly allocates values of 0 or 1 to the rows of
an array by “flipping a coin”:–
As a rule, you should try to avoid loop constructs in Matlab where this is possible -
especially for large arrays. Matlab is an interpreted language and this means that loops
execute slowly compared to compiled code. Loops are sometimes unavoidable and have
their place in the Matlab language and we shall say more about loop constructs later in
this section. The example below achieves the same purpose as the one above but uses
Matlab’s implicit vectorization capabilities
Comments
Note how the Matlab code is very compact and that the output of one function
can directly constitute the input to another (e.g. find(rand.. etc) )
For example :–
Here, dims is a 2 element row vector containing the number of rows and number of
columns. Try the following :–
This time, dims is a 3 element row vector because A is an RGB colour image and RGB
colour images are a composite of three separate 2-D images, one each for the red, green
and blue components.
Function Description
reshape Change the shape of an array
fliplr Orders the columns in reverse order
flipud Orders the rows in reverse order
tril Extracts lower triangular part of array
triu Extracts upper triangular part of array
rot90 Rotates array counter-clockwise by 90 o
Relational operators can be used to compare two arrays or an array to a scalar. The output
of all relational expressions produces logical arrays with 1 where the expression is True
and 0 where it is False. Thus, if A = [ 1 3 2 6] and B = [0 4 3 4], then A < B = [0 1 1 0].
Note that comparison takes place on an element by element basis, returning 1 where the
relation is satisfied and 0 where it is not. Note also the difference between the relational
equality (==) and the assignment operator (=).
Warning !
== and = are distinct operators.
The relational operator == tests for the equality of quantities; the assignment operator = is used to
assign the output of an operation to a variable. This is a common source of error, especially for
beginners.
Logical operators
Logical operators allow us to combine or negate relational expressions. Applying these
operators to relational expressions also results in logical (0-1) arrays having value 1
where the expression is TRUE and 0 where it is FALSE.
The basic logical operators in Matlab are given in the table below. Some examples of
their use is illustrated below :-
Note from the last example how the output from the function find can directly form the
input to the function isempty. This is possible in this specific case because the output
from find is a single array/matrix and the required input to isempty is also a single
array/matrix. The reader should consult the online help facility for further details of the
logical functions described above .
If statements
Matlab supports these variants of the if construct -
if …(statement)... end
if …(statement)... else …(statement)... end
if …(statement)... elseif …(statement)... else …(statement)... end
Note
no semicolon is needed to suppress output at the end of lines containing if, else,
elseif or end.
The operator == (is equal to) is used for logical comparison. It is quite distinct
from the single = sign which assigns a value to a variable.
Indentation of if blocks is not required, but considered good style.
Test your function on one or two of the Matlab images to make sure it operates properly.
Switch-case constructs
A switch-case construct is similar in basic purpose to an if construct. If a sequence of
commands must be conditionally evaluated based on the equality of a single common
argument, a switch-case construct is often easier. Here is an example :–
Comments
• The Matlab function imfinfo attempts to infer the contents of the image
cameraman.tif. It assigns the results to a structure called info (a structure is
essentially a collection of numeric and string variables each of which can be
accessed using the same basic name but a different specific field).
Type >> help struct at the Matlab prompt for further information
• One of the fields in this particular structure is the Format field. The switch statement
effectively registers/records the string contained in the format field.
• This is compared for equality with each of the strings contained within the curly
braces { } that are part of the case clauses.
• If equality occurs, the commands following the case clause are executed.
Thus the corresponding group of legal Matlab statements will be executed if the case
expression matches the switch expression.
for x = array
statements..
end
The for loop basically works by assigning the loop variable x to the next column of the
vector array at each iteration. Consider the following simple for loop to sum all the
integers from 1 to 10 :–
Thus, in this for loop the variable i takes on the next value in the array (1,2,..10) on each
successive iteration. The next example shows a slightly more advanced piece of code
involving some new Matlab functions - we include it now to show that the basic
construction of the for loop is exactly the same :–
The following example creates a vector with the first 16 terms of the Fibonacci series
xn+1 = xn + xn−1 using a for loop. Another for loop is then used to cyclically permute the
terms to form the rows of the image :–
while loops
The syntax of the while loop is very simple -
while expression
statements
end
In the while loop, expression is a logical expression and the statements following are
repeatedly executed until the expression in the while statement becomes logically false.
Here are a couple of simple examples :-
This example successively generates sets of 4 random numbers in the interval 0-1. The
loop stops when we obtain a set of 4 numbers all of which are less than 0.25.
We end this primer with an overview of some of the more advanced aspects of indexing
into arrays. Indexing into an array is a means of selecting a subset of elements from the
array. Indexing is also closely related to another term we mentioned in passing early on:
vectorization. Vectorization means using Matlab language constructs to eliminate
program loops, usually resulting in programs that run faster and are more readable. Try
out the following examples which illustrate a number of powerful indexing techniques.
Indexing Vectors
Let's start with the simple case of a vector and a single subscript. The vector is:-
>> v([1 5 6]) % Extract the first, fifth, and sixth elements
% ans = 16 2 11
Matlab's colon notation ( : ) provides an easy way to extract a range of elements from v:-
The special end operator is an easy short-hand way to refer to the last element of v -
The colon operator is very powerful and can be used to achieve a variety of effects :–
By using an indexing expression on the left side of the equal sign, you can replace certain
elements of the vector.:-
Usually the number of elements on the right must be the same as the number of elements
referred to by the indexing expression on the left. You can always, however, use a scalar
on the right side.
>>v([2 3]) = 30 % Replace second and third elements by 30
%v = 16 30 30 20 2 11 7 1 4
Most often, indexing in arrays is done using two subscripts - one for the rows and one for
the columns. The simplest form just picks out a single element :–
More generally, one or both of the row and column subscripts can be vectors.
The diagram below illustrates a trickier use of two-subscript indexing. The expression
A([2 3 4], [1 2 4]) does NOT extract elements A(2,1), A(3,2) and A(4,4) as one might, at
first glance think, but rather extracts the elements shown on the right :–
Linear Indexing
We begin with a question. What exactly does this expression A(14) do ?
When you index into the array A using only one subscript, MATLAB treats A as if its
elements were strung out in a long column vector by going down the columns
consecutively, as in :–
16
5
9
…..
8
12
1
The expression A(14) simply extracts the 14th element of the implicit column vector.
Here are the elements of the matrix A along with their linear indices in the top left corner
of each square:-
The linear index of each element is shown in the upper left. From the diagram you can
see that A(14) is the same as A(2,4) – i.e. Linear index = (column number – 1) x (number
of rows in array) + row number
The single subscript can be a vector containing more than one linear index, as in:
Let’s consider again the problem of extracting just the (2,1), (3,2), and (4,4) elements of
A. You can use linear indexing to extract those elements:
It’s easy to see the corresponding linear indices for this example, but how do we compute
linear indices in general ? provides a function called sub2ind that provides the
appropriate linear indices corresponding to the given row and column subscripts –
The in-built Matlab function ind2sub does precisely the reverse, providing the row and
column indices given the linear index and the size of the array.
In the following example we take two images A and B (of equal size) and compare them
on a pixel by pixel basis to see whether image A has the greater intensity. If so, we copy
the value in A to B.
Logical Indexing
Another indexing variation, logical indexing, has proved to be both useful and
expressive. In logical indexing, you use a single, logical array for the matrix subscript.
Matlab extracts the matrix elements corresponding to the nonzero values of the logical
array. The output is always in the form of a column vector. For example, A(A > 12)
extracts all the elements of A that are greater than 12.
Many Matlab functions that start with "is" (isnan, isreal, isempty..) return logical arrays
and are very useful for logical indexing. For example, you could replace all the NaNs4 in
an array with another value by using a combination of isnan, logical indexing, and scalar
expansion. To replace all NaN elements of the matrix B with zero, use:-
>> B=0./linspace(5,0,6)
>> B(isnan(B)) = 0
Or you could replace all the spaces in a string matrix str with underscores:-
Logical indexing is closely related to the find function. The expression A(A > 5) is
equivalent to A(find(A > 5)). Which form you use is mostly a matter of style and your
sense of the readability of your code, but it also depends on whether or not you need the
actual index values for something else in the computation. For example, suppose you
want to temporarily replace NaN values with zeros, perform some computation, and then
put the NaN values back in their original locations. In this example, the computation is
two-dimensional filtering using filter2. You do it like this :-
>>nan_locations = find(isnan(A));
>>A(nan_locations) = 0;
>>A = filter2(ones(3,3), A);
>>A(nan_locations) = NaN;
The Matlab indexing variants illustrated above give you a feel for ways we can create
compact and efficient code. You will certainly not need them all right away but learning
to include these techniques and related functions in your Matlab programs helps to write
and create efficient, readable, vectorized code.
4
NaN is the I.E.E.E. representation for Not-a-number. A NaN results from mathematically undefined
operations such as 0/0 or inf/inf. Any arithmetic operation involving a NaN and a legal mathematical entity
results in a NaN. They ca, however, sometimes be useful to identify and/or label locations at which data is
missing.
In this brief introduction, we have tried to give an indication and some simple examples
of some of Matlab’s key programming constructs – hopefully enough to get you off the
ground. There are now many good core Matlab books (non image processing specific)
and a significant amount of web-based material specifically aimed at helping users
develop their knowledge of the Matlab language and we refer the reader to a selected
sub-set of this material on the book website (with these primers).
We must also make mention of the excellent on-line help resources and comprehensive
documentation available to Matlab users. In the authors' experience it is clearly written,
well organized and both quick and easy to use – it almost (but we hope not quite) makes
the these two supporting Matlab primers for this book superfluous. We hasten to
recommend this material to the reader.
As a rather keen DIYer, I cannot help but compare programming in Matlab with
undertaking some task of physical construction such as building a house. It is a simple
but accurate analogy. Building a basic house can actually be done with a bare minimum
of essential tools but it tends to be long-winded and hard work. I have often had the
experience of beginning or even completing a particular task in building or carpentry
only then to discover that there is actually a much easier way to do it, given the right tool
and approach. If only one had known beforehand, how much time and effort could have
been saved !
I look upon the basic knowledge of variable types, arrays and indexing and key
programming constructs such as for and while loops, conditional if clauses etc that we
have discussed as the essential tools. However, many of Matlab’s in-built functions are
very much akin to specialist tools – they make easy that which is much harder if you try
to do it all yourself. These days, when I am in a hardware store, I often just browse the
tool section to see what’s available just in case I should ever encounter a future job which
could make good use of some specialist tool I encounter. In this spirit, we finish this very
brief introduction by providing the reader with a selected but large list (by category) of
Matlab functions together with a brief description of their purpose. Please browse at your
leisure. The completely comprehensive list is, of course, available in Matlab’s
documentation and the help facility.
This is a book about image processing so, finally, note that the specialist functions
associated with the Matlab image processing toolbox are not yet given here. The use of
many of these specialist image processing functions is discussed and demonstrated in the
remaining chapters of this book. A comprehensive list of functions available is available
in the Matlab image processing toolbox documentation.
ELEMENTARY
MATRICES
Matlab function Description
zeros Zeros array
ones Ones array
eye Identity matrix
repmat Replicate and tile array
rand Uniformly distributed random numbers
randn Normally distributed random numbers
linspace Linearly spaced vector
logspace Log spaced vector
freqspace Frequency spacing for frequency response
meshgrid X and Y arrays for 3-D plots
accumarray Construct an array with accumulation
BASIC ARRAY
INFORMATION
size Size of array
length Length of vector
ndims Number of dimensions
numel Number of elements
disp Display matrix or text
isempty True for empty array
isequal True if arrays numerically equal
isequalwithequalnans True if arrays numerically equal
MULTI-DIMENSIONAL
ARRAY FUNCTIONS
ndgrid Generate arrays for N-D functions and interpolation
permute Permute array dimensions
ipermute Inverse permute array dimensions
shiftdim Shift dimensions
circshift Shift array circularly
squeeze Remove singleton dimensions
MATRIX MANIPULATION
cat Concatenate arrays
reshape Change size
diag Diagonal matrices and diagonals of matrix
blkdiag Block diagonal concatenation
tril Extract lower triangular part
triu Extract upper triangular part
fliplr Flip matrix in left/right direction
flipud Flip matrix in up/down direction
flipdim Flip matrix along specified dimension
rot90 Rotate matrix 90 degrees
: Regularly spaced vector and index into
matrix
find Find indices of nonzero elements
end
sub2ind Last index
ind2sub Linear index from multiple subscripts
SPLINE INTERPOLATION
spline Cubic spline interpolation.
ppval Evaluate piecewise polynomial.
GEOMETRIC ANALYSIS
delaunay Delaunay triangulation.
delaunay3 3_D Delaunay tessellation.
delaunayn N_D Delaunay tessellation.
dsearch Search Delaunay triangulation for nearest
point.
dsearchn Search N_D Delaunay tessellation for
nearest point.
tsearch Closest triangle search.
tsearchn N_D closest triangle search.
convhull Convex hull.
convhulln N_D convex hull.
voronoi Voronoi diagram.
voronoin N_D Voronoi diagram.
inpolygon True for points inside polygonal region.
rectint Rectangle intersection area.
polyarea Area of polygon.
POLYNOMIALS
roots Find polynomial roots.
poly Convert roots to polynomial.
polyval Evaluate polynomial.
polyvalm Evaluate polynomial with matrix argument.
residue Partial-fraction expansion (residues).
polyfit Fit polynomial to data.
polyder Differentiate polynomial.
polyint Integrate polynomial analytically.
conv Multiply polynomials.
deconv Divide polynomials.
MATRIX ANALYSIS
norm Matrix or vector norm.
normest Estimate the matrix 2 norm.
rank Matrix rank.
det Determinant.
trace Sum of diagonal elements.
null Null space.
orth Orthogonalization.
rref Reduced row echelon form.
subspace Angle between two subspaces.
LINEAR EQUATIONS
\ and / Linear equation solution; use "help slash".
linsolve Linear equation solution with extra control.
inv Matrix inverse.
rcond LAPACK reciprocal condition estimator
cond Condition number with respect to
inversion.
condest 1_norm condition number estimate.
normest1 1_norm estimate.
chol Cholesky factorization.
cholinc Incomplete Cholesky factorization.
lu LU factorization.
luinc Incomplete LU factorization.
qr Orthogonal
lsqnonneg Linear least squares with nonnegativity
constraints.
pinv Pseudoinverse.
lscov Least squares with known covariance.
FACTORIZATION UTILITIES
expm Matrix exponential.
logm Matrix logarithm.
sqrtm Matrix square root.
funm Evaluate general matrix function.
qrdelete Delete a column or row from QR
factorization.
qrinsert Insert a column or row into QR
factorization.
rsf2csf Real block diagonal form to complex diagonal
form.
cdf2rdf Complex diagonal form to real block diagonal form.