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.
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.
Each student should do the following steps in their own account individually.
  1. 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.
  2. Create a directory where you will store files for each of our subsequent labs. For example,
    $ mkdir -p $HOME/CSC262/labs/
  3. Throughout the semester, I recommend you create 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

  1. Open the MATLAB program by clicking on the dock icon of a 2×2 identity matrix.
    1
    0
    0
    1
    If you have customized your dock to eliminate this icon, you may simply type matlab at the command prompt.
  2. 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.
  3. To ensure that you finished the preparation correctly, type the following matlab command
    which gkern
    If it responds "'gkern' not found." please ask for help in completing your preparation.

Exercises

When all group members have completed the preparation, the entire group may begin working on the exercises together (using only a single student's Matlab session).

A. 1-Dimensional Arrays (aka Vectors)

  1. 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).
  2. What does the following assignment yield?
    D = 1:10
  3. What do you predict the following assignments yield? Verify your predictions.
    E = 1:2:10
    F = 20:-1:10
  4. 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:

B. 2-Dimensional Arrays (aka Matrices)

  1. 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?
  2. Create a copy of B named C
    C = B;
  3. Enter a command that calculates the sum of B and C.
  4. 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)

  1. Clear the variable D from your workspace as follows:
    clear D
  2. 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.
  3. 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.
  1. Enter the following array into your work space.
    E = [5 -3 7 -1 10];
  2. Matlab vectorizes comparisons also. What do you expect the following to produce?
    E < 0
  3. 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)
  4. Recall that we can use arrays to index other arrays. Using find, write an expression that shows only the negative values in E.
  5. 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)
  6. 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.
  7. 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

  1. 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.)
  2. 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.
  3. 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)
  4. Remember that B is 2-D. What do you expect the following operation to produce? Check your answer.
    sum(B)
  5. 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 documentation for sum to calculate the sum along the columns of B (that is, sum up the rows).
  6. Use sum to create a matrix that is the average of the slices in D.
  7. 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.)
  8. 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.)
  9. Write an expression that calculates the sum of all the elements of B and D, respectively.
  10. 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.
  1. To recapitulate, you should still have variables A, B, C, D, and now E in your workspace. If not, reconstitute them now.
  2. The procedure
    B = arrayfun( fun)
    takes a function handle fun and an array variable. Use this to apply anotherFunHandle above to your matrix B.
  3. Define another matrix F that is 1×3 and contains any numeric values you like.
  4. What do you expect to happen if you execute the following line?
    B-F
    Verify your prediction.
  5. While mathematics allows you to 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). Matlab handles this for you by automatically expanding the size of one value to match that of the other.1

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).
  1. Type clear to remove all variables from your workspace
  2. 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.
  3. 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?
  4. 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).
  5. Display the image using imshow(I).
  6. 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

  1. 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?
  2. 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.
  3. Display the result in another new window using imshow.
  4. The procedure rgb2gray converts to a grayscale image using a more "realistic" formula
    I=0.3R+0.59G+0.11B.
    Use this procedure to create another grayscale image and display it.
  5. How does this compare visually to the single bands and the "averaged" grayscale version you compared?

I. Miscellaneous

A few steps should become regular practice for you.
  1. Download the sample file houghlab.m as documented on the submitting page and intro.m from our Matlab tutorial.
  2. Skim the documentation for the Matlab function checkcode, which is known as a "linter" (a program that statically checks program text for potential issues).
  3. Apply checkcode to houghlab.m and intro.m. Read through any issues it flags, make sure you understand why they might be issues, and how each could be fixed.
  4. Apply the publish command to houghlab.m to generate a PDF without code (as shown in the submitting page).
You should run checkcode on all of your submissions, and you must run publish to generate the PDF for submission.

Acknowledgments

Adapted from Lab 1: Intro to Matlab and Image Processing (CSSE 463 Image Recognition), Matt Bouttell.
Copyright © 2010, 2012, 2015, 2019 Jerod Weinman.
ccbyncsa.png
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 4.0 International License.

Footnotes:

1This is relatively new behavior in Matlab. You can read the history and changes here: https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b/