Matrices

# 1. Matrices

## 1.1. Objective

• To show how matrices can be created in MATLAB.
• To introduce the double index notation associated with matrices in a computer program.
• To introduce single index notation for accessing and assigning elements of a matrix.

## 1.2. Motivation

• Images are two-dimensional. Arrays are one-dimensional. We need a two-dimensional programming structure that can handle images easily.
• The matrix is an often-used method for describing information.
• To do computation on complex objects, such as images, you need to understand other ways of structuring the numbers that correspond to the values you see in the image.

## 1.3. Creating a matrix: assigning each element

To create the matrix M:

1.1   2.2
3.3   4.4
5.5   6.6


each position in the matrix can be specified be entering each value and position manually:

M(1,1) = 1.1; % Set row 1, column 1 to be 1.1
M(2,1) = 3.3; % Set row 2, column 1 to be 3.3
M(3,1) = 5.5; % Set row 3, column 1 to be 5.5
M(1,2) = 2.2; % Set row 1, column 2 to be 2.2
M(2,2) = 4.4; % Set row 2, column 2 to be 4.4
M(3,2) = 6.6; % Set row 3, column 2 to be 6.6


Note the following format when referring to positions of a matrix: NAME(row,column) where NAME is the name of the matrix and row,column refers to the row number and column number, respectively.

## 1.4. Creating a matrix: short-hand method

 Similar to an array, a matrix is a container for a list of numbers and it is also a data structure (recall that a data structure is used to organize a collection of numbers). A matrix has "shape". To create the matrix: 1.1 2.2 3.3 4.4 5.5 6.6  use array notation to indicate columns (by separating numbers with commas or spaces) and indicate new rows with a semicolon: M = [1.1, 2.2; 3.3, 4.4; 5.5, 6.6] 

A position in a matrix is identified by its row and column. Rows are numbered starting at the top of a column. Columns are numbered starting from the left (think of a column like an architectural structure)

Note that each row must have the same number of values. Entering:

M = [1.1, 2.2; 3.3; 5.5, 6.6]


will result in an error message. Only one value has been specified for the second row, and MATLAB will not assume that the unspecified column of the second row should be zero, and it will not assume which column the number given should be placed in.

## 1.5. Creating a matrix: appending matrices

To create the matrix:

1.1   2.2
3.3   4.4
5.5   6.6
1.1   2.2
3.3   4.4
5.5   6.6


we could enter:

M  = [1.1, 2.2; 3.3, 4.4; 5.5, 6.6];
M2 = [M;M];


the first command creates a 3x2 matrix. The second command stacks the matrix M onto a copy of itself. To place the matrices side-by-side, use the following command:

M3 = [M,M]

M3 =

1.1    2.2    1.1    2.2
3.3    4.4    3.3    4.4
5.5    6.6    5.5    6.6


MATLAB has the function repmat that allows matrices to be repeated. To create M2, the syntax is

M2 = repmat(M,2,1) % The 2,1 means two rows of M and one column of M.


and to create M3, the syntax is

M3 = repmat(M,1,2) % The 1,2 means one row of M and two columns of M.


## 1.6. Unspecified values in a matrix

If you entered

clear;
M(10,10) = 10.7


MATLAB assumes that you want a matrix with 10 rows and 10 columns (10x10 matrix) with the value in row 10 and column 10 to be 10.7:

M =

0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0         0
0         0         0         0         0         0         0         0         0      10.7


This is similar to when an array is created:

clear;
B(10) = 10.7


In this case, an array with 10 elements is created with zeros for the first nine elements and 10.7 for the tenth element.

## 1.7. Creating a matrix: special functions

• ones(M,N) creates a MxN matrix of ones. This is often used to create other uniform matrices, e.g., M = 99*ones(10,3).
• zeros(M,N) creates a MxN matrix of zeros.
• eye(M,N) creates a MxN matrix with ones on the diagonal and zeros elsewhere.
• rand(M,N) creates a MxN matrix with random values in the open interval (0,1).
• randn(M,N) creates a MxN matrix with values drawn from a gaussian (normal) distribution with zero mean and unit standard deviation.
• randi([Imax,Imin],M,N) creates a MxN matrix with random integer values in the range Imin through Imax.

Note that these functions have many additional options that can be found by using the help function (e.g., help randi).

## 1.8. size and numel

The size function returns an array with the number of rows and number of columns of the input matrix:

A = ones(10,5);
S = size(A)
ans =

10     5


If only the number of rows or columns is desired, the second argument can be used

Nrows = size(A,1)
Ncols = size(A,2)


or equivalently,

Nrows = S(1);
Ncols = S(2);


The numel function returns the number elements in a matrix.

Nel = numel(A); % Gives 50


Note that the same result can be achieved using the prod function, which returns the product of all elements in a vector

Nel = prod(size(A)); % Gives 50


## 1.9. Accessing array elements review

The third value of this array:

A = [1, 4, 2, 5, 3, 6]


can be accessed by entering:

A(3)


on the command line. The result will be:

ans =
2


## 1.10. Accessing matrix elements with double index notation

Given this matrix:

B =
1     4
2     5
3     6


the third row and first column would be accessed using double index notation:

B(3,1)


If you entered this on the command line, the response will be:

ans = 3


## 1.11. Accessing matrix element with single index notation

The third row and first column may also be accessed using single index notation, meaning only one number is used instead of two. Referring to the matrix

B =
1.1  5.5
2.2  6.6
3.3  7.7
4.4  8.8


The statement B(5) is interpreted as the 5th element of the matrix B, which is 5.5. MATLAB counts elements by counting down the first column until it hits the bottom and then continues counting at the start of the second column. This is called column major ordering. Some programs use row major notation, in which case the second element of B is 5.5, the third element is 2.2, etc.

Multiple elements of B can be accessed and modified using single index notation:

B(1:3) = 99;


gives

B =
99   5.5
99   6.6
99   7.7
4.4  8.8


## 1.12. Scalars and vectors are matrices in MATLAB

Thus far, scalars and vectors have been treated as separate types of data structures in MATLAB. In fact, they are both matrices. In MATLAB, a scalar is 1x1 matrix. To see this, enter

a = 1;
a(1,1)


which will display ans = 1.

Note also that if you enter whos a, you will see

  Name      Size            Bytes  Class     Attributes

a         1x1                 8  double


which indicates that a has dimensions of 1x1 (and the amount of memory used by the variable is 8 bytes).

A row vector with N columns is a 1xN matrix, and a column vector with M rows is a Mx1 matrix. If

A = [1:5]; % row vector


the fourth element can be displayed using A(1,4) or A(4). If

A = [1:5]'; % column vector


the fourth element can be displayed using A(4,1) or A(4).

## 1.13. Modifying or accessing a subset of a matrix

Thus far, we have modified or inspected only a single element of a matrix:

M = [1,2;3,4];
M(2,1) % Display row 2, column 1 (using double index notation)
M(4) = 99 % Replace the fourth element in matrix (the 4) with a 99 (using single index notation)
M(3) % Display the third element (the 2) of matrix (using single index notation)


In MATLAB, we can modify multiple elements of a matrix by specifying the values to be replaced with index arguments to the matrix:

M = [1,2;3,4];
M([1:2],1) = [77;88] % Modify rows 1 and 2 in first column of M
M([1:2],1) % Display rows 1 and 2 in first column of M


In the above example, the index argument is [1:2] was used for the rows of the matrix.

In the above example, we selected a column in the matrix and specified the replacement values with a column vector on the right-hand-side. This is actually not necessary - the following does the same:

M = [1,2;3,4];
M([1:2],1) = [77,88]


One may think that this should have resulted in an error because we have replaced a column vector on the left-hand side with a row vector on the right-hand side. However, because there is no ambiguity with what should be replaced, MATLAB allows the operation to work.

Another case where the selected matrix on the left-hand side does not need to match the replacement matrix given on the right-hand-side is when the right-hand-side is a scalar:

M([1:2],1) = 99 % Set values in rows 1 and 2 of M to 99


In the case that what is selected on the left-hand side is a matrix, the dimensions of its replacement much match the replacement matrix. For example,

M = [1,2,3;4,5,6] % Matrix with 2 rows and 3 columns
M([1:2],[1:3]) = [11,12,13;14,15,16]; % This will work; dimensions of selected matrix (2x3) matches replacement matrix (2x3).
M([1:2],[1:3]) = [11,12;13,14;15,16]; % This will not work; dimensions of selected matrix (2x3) does not matche replacement matrix (3x2).



In addition, single-index notation may be used:

M = [1,2;3,4];
M([1:3]) = [11,22,33]


gives

M =

11    33
22     4


and

M([1:3]) = 44


gives

M =

44    44
44     4


Note that when using single index notation on the left-hand side, the right-hand side can be either a scalar or a matrix with the number of elements matching the the number of selected elements. For example,

M = [1,2,3;4,5,6]
% M =
%
%   1     2     3
%   4     5     6
Mr = [11,12,13;14,15,16]
% Mr =
%
%    11    12    13
%    14    15    16
M([1:6]) = Mr % Works
% gives
% M =
%
%    11    12    13
%    14    15    16


and

M = [1,2,3;4,5,6]
% M =
%
%     1     2     3
%     4     5     6
Mr = [11,12;13,14;15,16]
%Mr =
%
%    11    12
%    13    14
%    15    16
% gives
M([1:6]) = Mr % Works!
%M =
%
%    11    15    14
%    13    12    16


## 1.14. The find function

The find function will return the location, in single index notation, where a matrix satisfies a logical constraint.

M = [9,10;11,12]
I = find(M > 10)


gives

M =

9    10
11    12

I =

2
4


The find function is often used to modify certain elements in a matrix. For example, to replace all values in M that are greater than 10 with 0, one could write

I = find(M > 10);
M(I) = 0;


One could also write M(find(M > 0)) = 0 and not create the intermediate variable I.

## 1.15. Matrix manipulation

### 1.15.1. transpose

transpose is used to create a new matrix has columns that are rows of the original matrix.

M = [1,2,3;4,5,6]
%M =
%
%     1     2     3
%     4     5     6
transpose(M)
% ans =
%
%     1     4
%     2     5
%     3     6


### 1.15.2. reshape

reshape is used to create a new matrix has same number elements but different dimension.

In the following example, a 1 row and 6 column array is created and the reshape function is used to create a matrix. The array is reshaped to have 2 rows and 3 columns. The number of elements in the A exactly matches the number of elements in M

A = [1:6]
M = reshape(A,2,3)
M =

1     3     5
2     4     6


to convert M back to having the same shape as A,

reshape(M,1,6)


Alternatively, one can use the single index selection shorthand:

M(:)


to convert a matrix to an array.

### 1.15.3. rot90

rot90 is used to create a matrix that is the original matrix rotated by 90 degrees counter clockwise.

M = [1,2,3;4,5,6]
%M =
%
%     1     2     3
%     4     5     6
rot90(M)
%ans =
%
%     3     6
%     2     5
%     1     4


### 1.15.4. flipud

flipud is used to create a new matrix that is the original matrix vertically inverted.

M = [1,2,3;4,5,6]
%M =
%
%     1     2     3
%     4     5     6
flipud(M)
%ans =
%
%     4     5     6
%     1     2     3


### 1.15.5. fliplr

fliplr is used to create a new matrix that is the original matrix horizontally inverted.

M = [1,2,3;4,5,6]
%M =
%
%     1     2     3
%     4     5     6
fliplr(M)
% ans =
%
%     3     2     1
%     6     5     4


## 1.17. Matrix functions

Many MATLAB functions perform operations on a matrix. For example,

M = [1:5;1:5;1:5];
mean(M) % or mean(M,1)


will compute the mean across dimension 1 (rows):

ans =

1     2     3     4     5


That is, the 1 indicates that the mean operation should be performed by averaging in the direction of increasing rows. The result is the column averages of the input matrix.

To compute the row averages of an input matrix, averaging should be performed in the direction of increasing columns.

mean(M,2) % Average in the direction of increasing columns (the second dimension, 2)

ans =

3
3
3


# 2. Problems

## 2.1. Matrix Syntax

What is wrong with each of the following statements?

clear;
M = [1.1; 2.2, 3.3 ; 5.5, 6.6]

clear;
M(0,1) = 1;
M(1,1) = M(0,1);


## 2.2. Scalars addressed as matrices

To display the value of an element of a matrix, you enter the row and column numbers desired in parenthesis, as in

M(2,2)


To create a scalar in MATLAB, one can enter

a = 1;


To see the value, you can enter

a


or

a(1)


or

a(1,1)


Explain why the last two options make sense.

## 2.3. Creating a matrix: assigning each element

Create the following matrix using by assigning each element.

M =

1     2     3
4     5     6
7     8     9


## 2.4. Creating a matrix: short-hand method

Use approach II for creating a matrix covered in Matrices to create a matrix named M that has the following elements:

 5   4   3
4   4   3
3   4   3
2   4   3
1   4   3


## 2.5. Creating a matrix: appending matrices

Create a matrix named M that has the following elements using the matrix appending method and using the function repmat.

 1   2   3
1   2   3
1   2   3
1   2   3
1   2   3
1   2   3
1   2   3
1   2   3


## 2.6. Creating a matrix

Using any method, write a set of commands that will create the following matrix.

-1 -2 -3
-1 -2 -3
1  3  3


## 2.7. Creating a matrix

Using any method, write a set of commands that will create the following matrix.

6 5 4 1 2 3
6 5 4 1 2 3
6 5 4 1 2 3
1 1 1 1 1 1


## 2.8. Creating a matrix

Using any method, write a set of commands that will create the following matrix.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35


## 2.9. Creating a matrix

Write a series of MATLAB commands that create the following matrix.

M =

1     2     3     4     5     6     7     8     9    10
2     3     4     5     6     7     8     9    10    11
3     4     5     6     7     8     9    10    11    12
4     5     6     7     8     9    10    11    12    13
5     6     7     8     9    10    11    12    13    14
6     7     8     9    10    11    12    13    14    15


## 2.10. Creating a matrix

Write a series of statements that creates a 10x10 matrix of all zeros except for ones on the border. Your answer must require fewer than 72 characters.

## 2.11. Accessing array elements

Explain the reason for error when the following commands are typed into MATLAB:

A = [1, 2, 3, 4]
A(2,2)


## 2.12. Accessing matrix elements

If you entered on the command line

C = [1.0, 2.0, 3.1 ; 4.2, 3.3, 5.5 ; 1.1, 12.0, 13.0]


what do you expect when you type

C(1) + C(2)
C(1,2) + C(2,2)
C(3,3) + C(3,3)


## 2.13. Accessing matrix elements

B =
1     4
2     5
3     6

• What is B(1,1) + B(2,2)?
• What is B(4) + B(5)?
C = [2.1,3.1 ; 4.1, 4.2 ; 5.1, 5.2]

• What is C(1,1) + C(2,2)?
• What is C(4) + C(5)?

## 2.14. Accessing matrix elements

If

M = eye(10)


write a single command that uses the end keyword to display rows 1-4 and columns 2-4 of M.

## 2.15. Accessing matrix elements

If

M = eye(1)


write a single command that will display only the elements that have a value of 1 in M. Hint: Use single index notation.

## 2.16. Accessing matrix elements

If

M = flilpr(eye(1))


write a single command that will display only the elements that have a value of 1 in M. Hint: Use single index notation.

## 2.17. Accessing matrix elements

1. Generate a 10x10 matrix with random integers in the range of 7 through 10 using the randi function.
2. Use the colon operator to display the values in the third row; do the same for the third column.
3. Write a command that will replace all values in the last column with 99.

## 2.18. Unspecified values in a matrix

Create a matrix by entering

clear
M(2,2) = 10.0


on the command line.

• What is the response?
• Why are the other values zero?
• Explain what happens when you type
M(2,1) = 13.0


## 2.19. Unspecified values in a matrix

What will happen when you enter the following commands?

M(1,2) = 99;
clear;
M(2,2) = 1.0;
M

clear;
M(2,2) = 4;
b = M(2,2) + M(1,2)


## 2.20. Modifying a subset of a matrix

Create the following matrix

M =

1 1 1
2 2 2
3 3 3


and then write a command that

1. sets all of the values in the second row to 99;
2. sets the values in the second row to be 22, 23, and 24.

Do this using the methods described in #Modifying or accessing a subset of a matrix

## 2.21. Modifying a subset of a matrix

Use the zeros function to create a 10x10 matrix. Modify this matrix so that all elements in the 4th row have the value of 99.

## 2.22. Modifying a subset of a matrix

What MATLAB statement in place of ?? could be used to create the output shown?

clear
M = zeros(3);
??
M =

1     0     0
0     2     0
0     0     3


## 2.23. Modifying a subset of a matrix

What MATLAB statement in place of ?? could be used to create the output shown?

M = zeros(5);
??
M =

0     0     0     0     0
1     0     0     0     0
0     1     0     0     0
0     0     1     0     0
0     0     0     1     0


## 2.24. The find function

The function imread reads the content of an image file and places the result in a matrix. Each matrix element represents a pixel in the image. The values in the matrix range from 0-255 and correspond to the level of white in each pixel, with 255 corresponding to white and 0 corresponding to black.

M = imread('cameraman.tif');
whos M % Display size of matrix that was read
M(1:2,1:2) % Display a few elements of the matrix
imshow(M)


Modify the above program so that image that is displayed is the original image except that any pixel value below 128 is set to 0.

## 2.25. Matrix manipulation

Use a combination of one or more of the functions flip, flipud, fliplr, and rot90 that will produce the same effect as transpose on a matrix.

## 2.26. Matrix manipulation

Use the reshape function to convert the matrix

M = [1,3;2,4]


to the row vector

[1,2,3,4]


using a single MATLAB command.

## 2.27. Matrix manipulation

Use the reshape command to conver the matrix

M = [1,3;2,4]


to the column vector

[1;2;3;4]


using a single MATLAB command.

## 2.28. Matrix manipulation

Use the reshape function and the transpose function to convert the array A=[1:100] to

M =

1     2     3     4     5     6     7     8     9    10
11    12    13    14    15    16    17    18    19    20
21    22    23    24    25    26    27    28    29    30
31    32    33    34    35    36    37    38    39    40
41    42    43    44    45    46    47    48    49    50
51    52    53    54    55    56    57    58    59    60
61    62    63    64    65    66    67    68    69    70
71    72    73    74    75    76    77    78    79    80
81    82    83    84    85    86    87    88    89    90
91    92    93    94    95    96    97    98    99   100


## 2.29. Matrix operations

Write long-hand syntax for the matrix operation M = A*B, where

A = [1,2;3,4];
B = [5,6;7,8];


That is, write the right-hand side of

M(1,1) =
M(2,1) =
M(1,2) =
M(2,2) =


in terms of only scalars, e.g., A(1,2), B(2,2), etc. and the + operator.

## 2.30. Matrix functions

Create a 200,100 matrix of values drawn from a gaussian distribution with zero mean and standard deviation of 10 and

1. compute the average of each column;
2. compute the standard deviation of each column using the std function.

## 2.31. Matrix functions

The mean2 function computes the average of all elements in a matrix. Given a matrix M

do you expect

mean2(M)


and

mean(mean(M))


and

mean(mean(M),2)


to always give the same result? If not, under what conditions will the results be the same?

## 2.32. Matrix functions

Given a matrix M of integers, do you expect

sum(sum(M))


and

sum(M(:))


to always give the same result? If not, under what conditions will the results be the same?

# 3. Video Tutorial

## 3.1. Video

(Note - the video is available in HD - go to full screen mode if fonts are too small)

## 3.2. Follow-up Questions

After watching the video (an pre-requisite videos), you should be able to answer the following questions.

### 3.2.1.

How is an array related to a matrix?

### 3.2.2.

The video on arrays included three methods for creating an array. This video only showed two methods for creating a matrix. What method was omitted?

### 3.2.3.

Create the following array using two different methods.

M =
1 2 3
4 4 4
8 8 8


### 3.2.4.

Write a command that will change the value of 8 in the third row and third column to 9.

### 3.2.5.

With only one command, create a matrix that has 10 rows and 10 columns, all with values of zero.