Lab: Matlab
CSC 262 - Computer Vision - Weinman
- Summary:
- Setting up your environment and getting practice with
some basic and essential MATLAB commands.
Deliverables
There is no formal write-up for this lab. Instead, you will create
your own Matlab "Quick Reference" guide. This has two purposes.
First, it will provide you a reference for useful functions or syntax.
Second, the process of recording it may actually help you remember
(about) what you recorded.
- Create an empty text (or other) file. As you work through the lab,
copy/write into it and briefly annotate (explain) things you want
to remember for later (e.g., functions, usage/syntax, etc.)
- Save this file as matlab-ref.txt and submit it.
This lab is likely to take you slightly longer than our class period,
but it is designed to be relatively straightforward practice in the
commands you will absolutely need to know to be efficient. You should
therefore plan to finish it (in it entirety) before our next lab.
Though you are not asked to submit answers to your exercises, if you
are unsure how to write any of the expressions that are asked for,
you should ask! They are designed to teach you how to do something
useful and important.
Preparation
Setting Up the Environment
Matlab is an interpreter-based programming environment. Like your
shell, it also has a path for determining where to look for scripts
or functions. In addition to the standard Matlab packages, you will
be using some specialized code for this course that we'll need to
make Matlab aware of.
- Copy the course-customized start-up file to your home directory (using
the shell command line):
-
$ cp ~weinman/courses/CSC262/toolbox/startup.m $HOME
If you examine this file, you will notice it adds to Matlab's path
a set of directories containing functions youll be using later. If
you decide to create your own function repository, you may modify
this file by adding commands using the same syntax.
- Create a directory where you will store files for each of our subsequent
labs. For example,
-
$ mkdir -p $HOME/CSC262/labs/
- I recommend creating a folder for each lab we do so you have one place
to store your write-up document, scripts, functions, and images in
an organized fashion.
Starting Matlab
- Open the MATLAB program by clicking on the dock icon of a 2×2
identity matrix.
If you have customized your dock to eliminate this icon, you may
simply type matlab at the command prompt.
- Explore the environment briefly to become comfortable with it. In
particular, the Command Window, the Command History,
and Workspace panes will be most useful. The first two are
fairly self-explanatory; the latter contains a list of all variables
(in scope) with some of their attributes.
Exercises
A. 1-Dimensional Arrays (aka Vectors)
- Enter the following commands one at a time into your Command
Window
-
A = [1 3 4 9 10]; % Create a 1x5 matrix called A
A % Displays the variable (when no semicolon)
B = 2*A % Creates a matrix B whose values are twice A's
C = A + B % Calculate the sum
Note how straightforward it is to do operations on an entire array
(generally called vectors when they are 1-dimensional in Matlab).
- What does the following assignment yield?
-
D = 1:10
- What do you predict the following assignments yield? Verify your predictions.
-
E = 1:2:10
F = 20:-1:10
- You can extract the values from an array in a variety of ways. Enter
the following commands one at a time, predicting what each will give.
-
A(1)
A(1:3)
A([1 3 5])
X = A(4)
After these exercises, you should note three very important things
about Matlab:
- 1-based subscripts Forget about C/Java/Scheme for the
time-being
- Flexible subscripting Another array can be used as a subscript
for multiple elements
- Parentheses () not brackets [] are used for subscripts Brackets
[] are used to construct arrays
B. 2-Dimensional Arrays (aka Matrices)
- Enter the following command into your Command Window
-
B = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
What does the semi-colon operator ; do?
- Create a copy of B named C
-
C = B;
- Enter a command that calculates the sum of B and C.
- What do the following commands do? Make your predictions and enter
them one at a time to verify.
-
B(2,3)
B(1:2,2)
B(3,:)
B(2,2:end)
B*C
B.*C
C. 3-Dimensional Arrays (sometimes aka images)
- Clear the variable D from your workspace as follows:
-
clear D
- 3-D arrays are a pain to enter manually. The following statements
each assign one 2-D "slice" of the array:
-
D(:,:,1) = [1 2 ; 3 4]
D(:,:,2) = [5 6 ; 7 8]
D(:,:,3) = [9 10 ; 11 12]
Note that when the right hand side of an assignment is an array (non-scalar),
the left hand side must index an array of the same size.
- Write a command that extracts the first column of the second slice
of D.
D. Fancy Indexing
As you've seen with addition, Matlab operate on entire matrices with
ease, much like the map function in Scheme. Such operations
are called vectorized since they avoid explicit loops. Thus,
you should avoid explicitly writing loops whenever possible.
- Enter the following array into your work space.
-
E = [5 -3 7 -1 10];
- Matlab vectorizes comparisons also. What do you expect the following
to produce?
-
E < 0
- Like C, Matlab treats anything non-zero as "true." The find
procedure returns the indices of an array that are "true" (non-zero).
What should this produce?
-
find(E < 0)
- Recall that we can use arrays to index other arrays. Using find,
write an expression that shows only the negative values in E.
- It turns out that so-called logical matrices (Matlab's equivalent
of a boolean type) can be used to extract the indices of another matrix
wherever there is a true value in the logical matrix. What does the
following produce?
-
E(E<0)
- What effect does the following have?
-
E(E<0) = 0
Note that when the right hand side of an assignment is a scalar, the
left hand side may be any size.
- The logical operators &, |, and ~ are used
for and, or, and not, respectively. Write an
expression that replaces all the values in E between 10 and
20 (inclusive) with -1.
E. Useful Functions
- The command
-
help function
displays some basic (and some times not-so-basic) information about
the command function in your command window. You can
open the same (and more) information in an interactive help window
by using the command
-
doc function
Use this functionality to create a matrix of all zeros that is 4×2.
using the zeros function. (Note that M×N will always
mean M rows by N columns.)
- You should have in your workspace a 1-D vector A, a 2-D matrix
B, and a 3-D matrix D from the previous exercises.
If not, copy these instructions from the initial exercises to recreate
all of them.
- We could write a loop to add all the elements of the vector in A,
-
tot = 0;
for k=1:5
tot = tot + A(k); % Matlab has no += (or ++) operator
end;
but given what we know about vectorized operations and loops, we would
probably think this is silly. What do you expect the result of the
following operation to be? Check your answer.
-
sum(A)
- Remember that B is 2-D. What do you expect the following
operation to produce? Check your answer.
-
sum(B)
- It turns out that built-in Matlab vectorized operations typically
operate along the first dimension (i.e., rows) by default unless
told otherwise. Use the documetantion for sum to calculate
the sum along the columns of B.
- Use sum to create a matrix that is the average of the slices
in D.
- The command
-
lookfor topic
searches for the keyword topic in Matlab's help files.
Use this to see if you can find a more direct way to calculate the
average of the slices. (Alternatively, you can use the help window's
search function directly.)
- A small clarification is in order: sum (and its kin) don't
actually operate on the first dimension. Rather, they operates along
the first non-singleton dimension. That is, the first dimension
that has a size greater than 1. What are the dimensions of the result
of sum(B)? (Hint: you may want to learn about the size
function.)
- Write an expression that calculates the sum of all the elements
of B and D, respectively.
- It turns out that Matlab, like C, stores all of the elements in any
array contiguously in memory (like a single array). Thus, it is very
easy to force matlab to treat this data as a K×1 array. You
can do this by using a single index into any array. Thus, D(6)
gives the 6th item in the array (as it is stored linearly). Write
an expression that uses only a single call to sum to find
the sum of all the elements in D.
(Hint: think of how you indexed variables earlier to get all the entries
along a particular dimension. What if you treat the variable as 1-dimensional?)
F. Function Handles
Like Scheme and C among other programming languages, Matlab can refer
to functions as first class values. Rather than invoke a function,
you can get a handle to a named function by preceding the name with
the @ sign, as follows:
-
myFunHandle = @sqrt
Unfortunately, unlike Scheme there is no elegant way to do composition.
You can also create anonymous or on-the-fly defined little functions
(much like Scheme's lambda) using the same operator, but
introducing an argument list:
-
anotherFunHandle = @(x) log(abs(x)+1)
This expression introduces a function that takes a single argument
(which we've named x). Unfortunately, you can only have a
single expression and no other bindings-in this way it is even more
functional in nature than Scheme! These sorts of function handles
(usually anonymous) are usually used for commands that do not vectorize
well.
- To recapitulate, you should still have variables A, B,
C, D, and now E in your workspace. If not,
reconstitute them now.
- The procedure
-
B = arrayfun( fun, S )
takes a function handle fun and a array variable.
Use this to apply anotherFunHandle above to your matrix B.
- Define another matrix F that is 1×3 and contains
any numeric values you like.
- What do you expect to happen if you execute the following line?
-
B-F
Verify your prediction.
- Unfortunately, while we can subtract a scalar from an array, using
syntax like X-5, if we are to subtract two arrays, they must
be the same size. Typically one wants to subtract
a vector (like F) from each row of a matrix (like B).
One approach is to use the procedure repmat to REPeat the
MATrix across the rows of A. The syntax is
-
Y = repmat(X,[m n ...]);
where m, n, (and so on) specify how many times to
repeat (or "tile") along the rows, columns, (and other dimensions),
respectively.
Use repmat to create a tiled version of the F that
is the same size as A so the two can be subtracted.
- The repmat solution works fine when speed and memory are
not an issue, but for larger matrices it can be very inefficient.
Fortunately, Matlab has bsxfun, (Binary [operator]
Singleton eXpansion) a function that can do
the repetition for you implicitly if you can specify the operation
you want to do with a function handle. Scan the documentation for
bsxfun and use it to subtract F from A
without using repmat.
G. Reading and Writing Images
The command window is much like the *nix shell: pwd gives
you the current directory (in case you didn't see it above), ls
and dir display the files and folders there, cd
moves you around (i.e., cd .. takes you to the parent directory).
- Type clear to remove all variables from your workspace
- Read a color image of your choosing into Matlab. For example,
-
I = imread('../Desktop/foo.jpg');
Note that Matlab file names (it's character string type) are enclosed
in single quotes.
- Use the command whos to see the names, sizes, and types of
all the work spaces variables. How big is your image? What type ("Class")
is it?
- Unless you read something very strange, your image should be a uint8
variable. This means its data values are unsigned, 8-bit integers
(i.e. values in 0-255).
- Display the image using imshow(I).
- Save a copy of your image using the following command
-
imwrite(I, 'filename.png');
Note that the extension automatically tells Matlab what format to
use. The TIFF format is uncompressed and would give us rather large
files. JPEG is lossy compression, which would give us image unwanted
artifacts. PNG is a compromise: its compression is not as great as
JPEG, but it is lossless.
H. Manipulating Images
- As indicated earlier, images are often 3-D arrays. Each slice represents
an array of the red, green, and blue color channels of the image (known
as R, G, and B, respectively) . We'll learn more about these later
in the course. You can extract and show bands of the image. For example,
-
Ir = I(:,:,1);
figure; % Opens a new figure window
imshow(Ir); % Displays the image in the new window
Extract and show the green and blue bands of the image. Which looks
most like what you'd expect the corresponding grayscale ("black
and white") image to look?
- A simple approximation of the grayscale image can be found by averaging
the three color bands. Unfortunately, the 8-bit format is usually
not appropriate for doing very complicated arithmetic with pixel values.
Instead, we convert the image to double, where instead of having discrete
values 0-255, the image takes on floating point values between 0 and
1. Matlab will do this for you:
-
I = im2double(I);
Do this conversion and then calculate a gray scale version by averaging
the three color bands.
- Display the result in another new window using imshow.
- The procedure rgb2gray converts to a grayscale image using
a more "realistic" formula
Use this procedure to create another grayscale image and display it.
- How does this compare visually to the single bands and the "averaged"
grayscale version you compared?
Acknowledgments
Adapted from Lab 1: Intro to Matlab and Image Processing (CSSE
463 Image Recognition), Matt Bouttell.
Copyright © 2010, 2012, 2015 Jerod
Weinman.
This work is licensed under a Creative
Commons Attribution-Noncommercial-Share Alike 4.0 International License.