CS 332

Lab:
MATLAB Introduction

The purpose of this lab is to learn how to work in the MATLAB environment, and to learn some basic MATLAB commands, including how to read and display images.

Start MATLAB

On your MAC, go to the Go>Applications folder and double-click on the MATLAB_R2017a icon.

The MATLAB desktop contains four inner windows:

The selection of subwindows that appear, and their spatial arrangement, can be controlled through the Layout menu that appears in the top region of the MATLAB desktop. Like other windows-based applications, you can change the size of the inner windows by dragging their borders, close the inner windows, and use scroll bars to navigate up and down the window contents. If your MATLAB windows change their appearance in an undesirable way, you can restore the original setup by selecting Default from the Layout menu.

Enter some commands in the Command Window

MATLAB is interactive - the user enters commands in the Command Window, MATLAB executes these commands, and the results are returned and printed. Enter the following MATLAB statements one-by-one in the Command Window (the % symbol precedes comments that you do not need to enter):


num = 10                 % create a variable named "num" whose value is 10

vals = [1 5 -3 7 0]      % create 1D vector (array) of numbers - note square brackets

num                      % print the value of an existing variable

format compact           % omit extra vertical space in future printout (see printout
                         % from next statement)

a = 2

b = 20.0;                % semi-colon at the end of a statement suppresses printout

clc                      % clear the Command Window - do the variables still exist?

whos                     % list variables currently defined in the MATLAB workspace
                         % (variables are also listed in the Workspace window)

c = (2 * num) + 3        % perform simple calculations

num = sqrt(c^3 + b^2)

area = pi * num^2        % pi is a built-in constant, note use of scientific notation 
                         % in printout of result

bignum = num/0           % note that this doesn't yield an error!

val2 = 5 * (4 + vals)    % perform calculations on an entire vector of numbers

val3 = [3 8 -4; -1 0 2]  % create a 2x3 matrix (2D array) of numbers - note the 
                         % semi-colon in the middle, separating the rows!

What happens if the number of elements in each row is not the same?

val4 = 5 * (4 + val3)    % perform calculations on an entire matrix of numbers

size(val3)               % get the dimensions of the matrix (result is returned 
                         % as a 1x2 vector)

size(val3, 1)            % second input is optional - what does it do?

size(val3, 2)

dims = size(val3)        % size function also has optional outputs that can be 
                         % assigned to one or two variables

[rows cols] = size(val3)

help cos                 % access MATLAB's help facility ...

doc randi                % ... or documentation pages

Using randi, write a statement that creates a 4x2 matrix of random integers 
between 1 and 10

Use the Command History to re-execute earlier commands

Execute a previous command again by double-clicking on the command in the Command History window, or by copying-and-pasting the command from the Command History into the Command Window and hitting the return key.

Use the arrow keys for command execution and editing

Use the four arrow keys to do the following:

Once a command is complete, it can be executed by hitting the return key, regardless of the position of the cursor in the line.

Open the MATLAB editor and create a script file of MATLAB code

MATLAB code files are referred to as M-Files and have a .m file extension. In this lab, we'll create a type of M-file called a script, which contains a sequence of MATLAB commands that can be executed all at once. Executing a script produces the same results that would be obtained if the individual commands were entered, one-by-one, in the Command Window.

Create a folder named Lab1 on the Desktop of your Mac, where you will save the code file that you create. In MATLAB, make this folder your Current Folder (current directory). You can do this by using either the arrow or folder icons directly above the Current Folder window to navigate up and down the directory tree. You can also use the pull-down menu above the Command Window to select a different folder. The Current Folder window should show the empty contents of your Lab1 folder.

MATLAB has a built-in editor for creating and viewing code files and text files. There are at least three ways to open an initial editor window, to create a new script file:

Enter some assignment statements in the editor, similar to those entered earlier in the Command Window. Save the script by clicking on the floppy disk icon labeled Save at the top of the editor window or use the Save menu below the icon. When saving for the first time, a dialog box appears, where you can enter the name of the script file. Enter either the first file name (e.g. lab1) or full file name (e.g. lab1.m) in the text box labeled Save As:. The box labeled Where: should contain your Lab1 folder. Click on the Save button, and your file will be stored in your Lab1 folder - check its listing in the Current Folder window.

Execute the script in the Command Window by entering the first file name lab1. If you did not place semi-colons at the end of your MATLAB statements, note the printout of variable names and values. Enter whos to see that your script variables exist in the MATLAB workspace.

Edit the script (for example, add or remove semi-colons at the end of existing statements or add new statements), save the modified file, and execute it again in the Command Window (note that a * appears at the end of the file name in the tab at the top of the code in the editor, when a modified file is not yet saved). You can also run your script by clicking on the green arrow icon at the top of the editor window.

An existing M-File can be opened in the MATLAB editor by clicking on the folder icon above the Open menu or by selecting Open... from the Open menu, and then navigating to the desired code file. You can also double-click on the file name in the Current Folder window, or invoke the edit command in the Command Window:

   edit lab1

The file (lab1.m in this case) must be stored in the current directory, or exist somewhere on MATLAB's search path, which we'll review in lab. Note that multiple code files can be open in the editor. The files are overlaid and can be selected by clicking on the tab with their file name near the top of the editor window. Create a new script file named lab2.m with a couple code statements, to experiment with switching between files.

Load and display an image

Use the imread function to load an image into MATLAB, and assign it to a variable:

   coins = imread('coins.png');      % note the semi-colon!

(The coins.png image comes with MATLAB's Image Processing Toolbox.) The image is now stored in a 2D matrix named coins - you can check its size by entering the whos command or checking the list of variables in the Workspace window. There are two ways to display an image. Display the image using imshow:

   imshow(coins)

The image will appear in a separate figure window. Examine the image more closely with imtool:

   imtool(coins)

Try the following:

Examine the changes in image intensity between adjacent image locations, around the borders of the coins and along the edges of the raised figures on the surface of the coins. Also note that even in regions that appear to have constant intensity, such as the dark background, the intensities do not have a constant value. Our first step in analyzing images will be to detect and describe the changes in image intensity - this information provides the first hint about the structure of the scene being viewed.

Close all of the open windows by executing the following two commands in the Command Window:

   close all
   imtool close all

More MATLAB

Determine what the following MATLAB statements do, based on the resulting printout.


mx1 = [3 6 1; 2 -1 4]   % create two 2x3 matrices
mx2 = [0 6 5; 1 3 2]

2 * (mx1 + 3)

ans                     % if a result is not assigned to a variable name, MATLAB
                        % automatically assigns it to the generic variable "ans"

mx1 + mx2

ans

mx1 - mx2

mx1 * mx2               % hmmm... to multiply (or divide) the contents of mx1 and
                        % mx2 "element by element", use the .* and ./ operators
mx1 .* mx2

mx1 ./ mx2

squares = mx1 .^ 2      % note that the result of any of the above expressions 
                        % could have been assigned to a variable

mx1'

nums = [3 6.2 -4 1.07]

nums(1)                 % how does array indexing differ between MATLAB and Python?

nums(5)

nums(end)

nums(3) = 13

sum(nums)

mx1(2,3)

mx1(1,2) = 9

sum(mx1)                % hmmm...

sum(sum(mx1))

min(mx1)                 

Write a statement to find the (single) minimum (or maximum) value of mx1

vals0 = zeros(2,3)

vals1 = ones(3,2)

Use zeros and ones to write two different statements that each create 
a 2 x 4 matrix that contains all 100's 

seq1 = 7:11             % "colon notation" will be used extensively

seq2 = 4:3:13

seq3 = 4:3:15

seq4 = 13:-2:7

mx1 = [1 3 0 5 6 8]

mx2 = [1 4 -1 7; 5 8 2 3]

mx1(2:4)

mx1(4:end)              % what does "end" refer to?

mx2(1,2:3)

mx2(:,2:3)

mx2(1,:)

mx2(2,:) = 7

mx2(1,2:3) = 4

mx1(1:2:end) = 0

clear all

whos

Use your new MATLAB skills to create and display the image shown below. The image should have 200x200 pixels, and should have values ranging from 0 (black) to 255 (white). When displaying the image, provide a second input that is empty brackets, e.g. imshow(myImage, [])

Quit MATLAB

When you are done, quit out of MATLAB by selecting Quit MATLAB from the MATLAB menu at the top of the computer screen.