Matlab Matrix Operations
Matlab Matrix Operations
Matlab Matrix Operations
From MATLAB® Programming, David C. Kuncicky. Copyright © 2004 by Pearson Education, Inc. All rights reserved.
Arrays and Matrix Operations 255
Arrays and Matrix Operations
You can create arrays and matrices several ways in MATLAB. You have already been
shown how to enter arrays in the Command window by typing text commands. There
are several other ways to enter arrays in MATLAB. You can enter arrays by loading a
script file that creates the arrays. You can view and edit arrays and matrices by using a
graphical user interface called the Array Editor. Finally, you can quickly enter several
types of special matrices by using some of MATLAB’s built-in matrix generators.
To see the Array Editor window, you should double-click anywhere on the line of
the variable that you want to edit. In our example, click the mouse on the variable A in
the Workspace window. The Array Editor will appear as depicted in Figure 2.
From the Array Editor, you can click on any cell in the array and edit the cell con-
tents. You, can also change the array dimensions by changing the sizes in the window ti-
tled “Size”. You can modify the display format by choosing a format from the drop-down
menu titled “Numeric format”.
2.3 Formatting Output
Numbers may be formatted several ways for display on the screen. The formatting
does not affect the way the numbers are stored internally. Table 1 describes the MAT-
LAB numeric formats. The numeric formats that you choose in the Array Editor win-
dow will return to the default of type “short” when you exit MATLAB. If you want to
save your favorite format, then choose File : Preferences : Array Editor from
the Menu bar. Preferences saved in this manner will persist when you exit and restart
MATLAB.
Arrays and Matrix Operations 257
Arrays and Matrix Operations
You can also modify the display format by using the format command in the Com-
mand window. In addition, you can change the display format by choosing File :
Preferences : Command Window from the Menu bar. The syntax of the format
command is
format format-type
format ('format-type')
format
where format-type is one of the types listed in Table 1. Note that every MATLAB com-
mand may be represented in command form or functional form. The command form
uses the command name followed by one or more spaces and then uses the command
arguments—for example,
>> format long
The functional form uses the command named, followed by the arguments (if any) in
parentheses. When using the functional form, you must place quotes around a string
argument—for example,
>> format ('long')
We will not repeat the functional form in every example in the text, but it is understood
that it may be used in place of the command form. The functional form is useful when
programming because it allows you to manipulate the argument as a variable.
The format command without arguments resets the format to the default type.
The default format is “short”.
In addition to numeric formats, the compact and loose formats may be used to add
or to delete extra line feeds in the display. Here are some examples:
>> format loose
>> log(2)
ans =
0.6931
>> format compact
>> log(2)
ans =
0.6931
258 Arrays and Matrix Operations
Entering Arrays and Matrices
If you forget what format you are utilizing, you can display the current format by using
the get function. The get function gets an object attribute—in this case, the format at-
tribute. The first argument is the number of the graphics object that contains the at-
tribute. A graphics object in MATLAB is simply a named graphical structure (e.g., the
Command window). The object number for the Command window screen is 0, as shown
here:
>> get(0, 'format')
ans =
long
As an aside, you can see all of the attributes for an object by using the get function with
the object number alone as an argument. The following command returns all of the at-
tributes of the Command window:
>> get(0)
CallbackObject = []
Language = english
CurrentFigure = []
Diary = off
DiaryFile = diary
Echo = off
ErrorMessage = Error: Expected a variable,
function, or constant, found “)”.
FixedWidthFontName = Courier
Format = long
...
(many more lines of output)
We call a matrix in which all of the elements are the number one a ones matrix. You
can create a ones matrix by using the ones function. The syntax of the ones function is
identical to the syntax of the zeros function. The following command creates a 3 * 2
matrix of ones:
>> A = ones(3, 2)
A =
1 1
1 1
1 1
Similarly, you can generate an array of pseudorandom numbers by using one of MAT-
LAB’s several random array generator functions. One of these, the rand function, gener-
ates an array of random numbers whose elements are uniformly distributed in the range
(0, 1). A uniform distribution is one in which there is an equal probability of occurrence
for any value within the given range (0, 1)—for example,
>> A = rand(2,5)
A =
0.9501 0.6068 0.8913 0.4565 0.8214
0.2311 0.4860 0.7621 0.0185 0.4447
Another commonly used matrix form is the identity matrix. An identity matrix is a matrix
in which every element of the main diagonal is one and every other element is zero. You
can generate an n * n identity matrix by using the eye function with the syntax, as
shown here:
eye(n)
Here is an example:
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
You can use two arguments to specify both dimensions. An m * n identity matrix with
ones on the diagonal and zeros elsewhere can be generated by using the syntax
eye(m,n)
For example, we might have
>> eye(4,3)
ans =
1 0 0
0 1 0
0 0 1
0 0 0
The eye function does not support more than two dimensions. Specifying more than two
dimensions will result in a syntax error—for example,
>> A = eye(3,4,5)
??? Error using ==> eye
Too many input arguments.
260 Arrays and Matrix Operations
Accessing and Manipulating Array Elements
ans =
3
>> A(8)
ans =
6
We have already used the colon operator to generate arrays. You can also use the colon
operator to access multiple array elements simultaneously. You do this by using the
colon operator to define a subscript range. For example, the use of 1:2:9 as a subscript
returns the first, third, fifth, seventh, and ninth elements of A:
>> A(1:2:9)
ans =
1 3 4 5 7
When used alone, the colon denotes all rows or columns. The following command re-
turns all columns of row two from array A:
>> A(2,:)
ans =
2 4 6
The following command returns the second and third rows of the first and second
columns from array A:
>> A(2:3, 1:2)
ans =
2 4
3 5
>> C = [A; B]
??? Error using ==> vertcat
All rows in the bracketed expression must have the same
number of columns.
PROGRAMMING TIP 1!
MATLAB supports preallocation of arrays by allowing (e.g., 20,000), create a zero-filled array by using
the creation of an array that is filled with all zeros or
zero(20000);
ones. If you are using very large arrays in your pro-
grams, preallocation is more efficient than slowly grow- which is much faster than extending the size of the array
ing an array. one element at a time.
If you know the size of your array ahead of time
>> A = [ 1 0 1 0
0 2 0 2
3 1 3 1 ]
Write commands that will perform each of the following operations on array A:
Re-create array A again before each problem. Check your answers by using MATLAB.
>> C = [1,3,5]
C =
1 3 5
>> D = [2,4,6;3,5,7]
D =
2 4 6
3 5 7
>> C + D
??? Error using ==> +
Matrix dimensions must agree.
As you see, attempting to add them will result in an error.
The addition of arrays is commutative—that is,
A + B = B + A.
The addition and subtraction of arrays is associative—that is,
A + 1B + C2 = 1A + B2 + C.
In this case (where at least one operand is a scalar), the period before the multiplication
symbol is not required. The “*” alone will produce the same result. (See Section 5.2, ti-
tled “Matrix Multiplication” for details.) Here’s an example:
>> A*B
ans =
10 20 30
>> A.^B
ans =
8 9 2
PRACTICE 2! Given
A = [2 0 2; 1 0 1]
and
B = [4 4 4; 9 9 9]
calculate the following by hand:
1. A + B
2. A * 3
3. A .* 3
4. A .^ 3
5. (A + B) ./ B
6. (A + B) ./ A
Use MATLAB to check your answers.
The MATLAB symbol for vector multiplication is the asterisk 1*2 —for example,
A = [1, 5, -6]
A =
1 5 -6
B = [-2; -4; 0]
B =
-2
-4
0
C = A * B
C = -22
The result was calculated as follows:
A*B = (1*-2) + (5*-4) + (-6*0) = -22
Note how this differs from array multiplication, which would fail, since A and B are not
conformable for array multiplication.
If you attempt to use nonconformable vectors, MATLAB returns an error. Here’s
an example:
>> A = [1, 2, 3]
A =
1 2 3
>> B = [2, 3, 4]
B =
2 3 4
>> A * B
??? Error using ==> *
Inner matrix dimensions must agree.
3x1 + 2x2 + x3 = 5
x1 + 2x2 + 3x3 = 13
-5x1 - 10x2 - 5x3 = 0
3 2 1 x1 5
C 1 2 3 S C x2 S = C 13 S
-5 -10 -5 x3 0
Arrays and Matrix Operations 269
Arrays and Matrix Operations
MATLAB uses a complex algorithm to compute the solution to a linear system of the
form AX = B. The operation is denoted by the matrix left division operator (the back-
slash) X = A \ B.
The solution to the preceding linear system can be determined as follows:
>> A = [3 2 1; 1 2 3; -5 -10 -5];
>> B = [5; 13; 0];
>> X = A\B
X =
2.5000
-4.5000
6.5000
Verify that MATLAB produced a correct answer by substituting the results into the orig-
inal three equations. You will learn more about solutions to linear systems when you take
a course in linear algebra.
Unary matrix operations are mathematical computations that are performed by using a
single matrix as an input.
6.1 Transpose
We call the matrix that is created by exchanging the rows and columns of matrix A the
transpose of A. For example, given
1 2 3
A = C4 5 6S
7 8 9
270 Arrays and Matrix Operations
Unary Matrix Operations
1 4 7
AT = C 2 5 8S
3 6 9
The MATLAB prime operator 1¿2 returns the transpose of its argument—for example,
>> A = [1, 2, 3; 4, 5, 6; 7, 8, 9]
A =
1 2 3
4 5 6
7 8 9
>> A'
ans =
1 4 7
2 5 8
3 6 9
6.2 Determinant
The determinant of a matrix is a transformation of a square matrix that results in a scalar.
We denote the determinant of a matrix A mathematically as ƒAƒ or det A. In this text, we
will use the second notation, since it resembles the MATLAB function for computing a
determinant.
If a matrix has a single entry, then the determinant of the matrix is the value of the
entry. For example, if A = [3], the determinant of A = 3. We write this as
det A = 3.
If a square matrix A has order 2, then the determinant of A is calculated as follows:
det 1A2
where A must be a square matrix—for example,
A =
2 3
6 4
>> det(A)
ans =
-10
First, we will show you how to calculate mathematically the determinant of a matrix
with order n 7 2. Then we will show you how to use MATLAB to perform the same
computation.
The strategy for calculating the determinant of a matrix with order n 7 2 involves
subdividing the matrix into smaller sections called minors and cofactors. If row i and col-
umn j of a square matrix A are deleted, the determinant of the resulting matrix is called
Arrays and Matrix Operations 271
Arrays and Matrix Operations
the minor of aij. We denote the minor as Mij. For example, given
1 2 3
A = C4 5 6S
7 8 9
then the minor of a12 (deleting row 1 and column 2) is
d.
4 6
M12 = detc
7 9
The cofactor of aij is denoted as Aij and is calculated as follows:
Aij = 1-12i + j Mij.
+ 6 # 1-122 + 3 # detc d
1 2
7 8
= 1-4 # -62 + 15 # -122 + 1-6 # -62
= 0.
There is a method for determining if and when the inverse of a matrix exists. It de-
pends on understanding the concept of matrix singularity. A square matrix is singular if
and only if its determinant is equal to zero. Otherwise, a matrix is nonsingular. Further-
more, a square matrix has an inverse if and only if it is nonsingular. So, a square matrix A
has an inverse if and only if det1A2 Z 0.
However, on a computer, zero is not always zero. Computer representations of real
numbers are usually approximations. Thus, calculations can result in highly accurate, but
approximate results. If the determinant of a matrix is close to zero, MATLAB will give a
warning that the inverse of A may not be correct.
The syntax for MATLAB’s inverse function inv is
inv(square-matrix)
Recall from the previous example that the determinant of the matrix
A =
1 2 3
4 5 6
7 8 9
is singular (i.e., det1A2 = 0 ) and should not have an inverse. MATLAB returns a warn-
ing noting this:
>> inv(A)
Warning: Matrix is close to singular or badly scaled.
Results may be inaccurate. RCOND = 1.541976e-
018.
ans =
1.0e+016 *
-0.4504 0.9007 -0.4504
0.9007 -1.8014 0.9007
-0.4504 0.9007 -0.4504
>> A^-2
ans =
5.5000 -2.5000
-3.7500 1.7500
This only works if the matrix is nonsingular. MATLAB issues a warning if the computed
determinant of A is equal or very close to zero. Here’s an example:
>> A = [1,1; 0,0]
A =
1 1
0 0
>> det(A)
ans =
0
>> A^-2
Warning: Matrix is singular to working precision.
ans =
Inf Inf
Inf Inf
7 MULTIDIMENSIONAL ARRAYS
A(:,:,2) =
1 1 1
1 1 1
MATLAB contains scores of useful functions for manipulating and extracting infor-
mation from arrays. This section presents a few of the most commonly used array
functions.
ndims
The ndims function returns the number of dimensions of its argument—for example,
>> A = ones(2,3,2);
>> ndims(A)
ans =
3
size
The size function returns the length of each dimension, or the order of the array. The re-
sult is a vector that contains the size of dimension 1, dimension 2, dimension 3, etc.
Here’s an example,
>> A = zeros(2,3,2,4);
>> size(A)
ans =
2 3 2 4
You can also use the size function to return the size of each dimension to a separate
variable—for example,
>> [m, n, s, t] = size(A)
m =
2
n =
3
s =
2
t =
4
diag
The diag function returns the elements of the main diagonal. For a matrix, diag re-
turns the elements with equal row and column indices (i.e., elements (1,1), (2,2),
(3,3), etc.):
>> A = [1 3 5; 2 4 6; 0 2 4]
A =
1 3 5
2 4 6
0 2 4
Arrays and Matrix Operations 275
Arrays and Matrix Operations
>> diag(A)
ans =
1
4
4
The main diagonal is also called the zero diagonal. A second argument may be passed to
diag that specifies the nth diagonal above or below zero. If the second argument is posi-
tive, the nth diagonal above the zero diagonal is returned, as in this example:
>> diag(A,1)
ans =
3
6
If the second argument is negative, the nth diagonal below the zero diagonal is returned.
Here’s an example:
>> diag(A,-1)
ans =
2
2
length
The length function returns the length of the largest dimension of an array. For a one-
dimensional array (vector), this equals the number of elements in the vector. The
length of A in the following example is three, which is the size of the largest dimension:
>> A = [1 3; 2 4; 0 2];
>> length(A)
ans =
3
reshape
The reshape function reshapes an array. It has the syntax
reshape(A, m, n, p, ...)
where A is the array to be reshaped, and m, n, p, Á are the new dimensions. The num-
ber of elements in the old array must equal the number of elements in the new array.
Consider the array
>> A = ones(2,6,2);
Since the number of elements in A = 2 * 6 * 2 = 24, we should be able to reshape A
into any order in which the product of the dimensions equals 24—for example,
>> reshape(A,2,12)
ans =
1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1
An attempt to reshape an array into a nonconforming array results in an error. Here’s an
example:
276 Arrays and Matrix Operations
Useful Array Functions
>> reshape(A,3,5)
??? Error using ==> reshape
To RESHAPE the number of elements must not change.
We shall consider another example. The following transformation makes sense, since
you know that MATLAB stores arrays in column-major order:
>> A = [ 1 2 3; 4 5 6; 7 8 9; 10 11 12]
A =
1 2 3
4 5 6
7 8 9
10 11 12
>> reshape(A, 2, 6)
ans =
1 7 2 8 3 9
4 10 5 11 6 12
sort
The sort function sorts arrays. When used on a vector, the sort is in ascending order:
>> A = [4 2 3 9 1 2];
>> sort(A)
ans =
1 2 2 3 4 9
When used on a two-dimensional array, MATLAB performs the sort on each column:
>> A = [5 0 4; 2 2 1]
A =
5 0 4
2 2 1
>> sort(A)
ans =
2 0 1
5 2 4
For more than two dimensions, MATLAB performs the sort on the first dimension with
the size greater than one. We call a dimension of size one a singleton dimension. Another
way of stating this rule is that the sort is performed on the first nonsingleton dimension.
You can specify the dimension on which to sort as a second argument. For exam-
ple, if we want to sort the two-dimensional array A across rows instead of down columns,
we could use the following command:
>> A = [5 0 4; 2 2 1]
A =
5 0 4
2 2 1
>> sort(A,2)
ans =
0 4 5
1 2 2
You can perform descending sorts by using the colon operator.
Arrays and Matrix Operations 277
Arrays and Matrix Operations
PRACTICE 5! Each of the five columns in matrix A represents the four exam grades for a student in
a MATLAB programming class:
A = [ 89 97 55 72 95
100 92 63 85 91
82 96 71 91 82
90 98 48 83 70 ]
1. Give a command that sorts each student’s grades and returns a matrix with the
sorted grades.
2. Give a command that computes the mean of each student’s grades and returns a
vector with the results.
3. Give a command that computes the median of each student’s grades and returns
a vector with the results.
4. Give a single command that returns the overall mean grade for all five students
in the course.
Now, change your view of matrix A. Assume that each of the four rows in matrix A
represents the five exam grades of a student. Note: Each row represents a student.
5. Give a command that sorts each student’s grades and returns a matrix with the
sorted grades.
6. Give a command that computes the mean of each student’s grades and returns a
vector with the results.
7. Give a command that computes the median of each student’s grades and returns
a vector with the results.
8. Give a single command that returns the overall mean grade for all five students
in the course.
278 Arrays and Matrix Operations
Key Terms
CITY 1 0 1 1 2
CITY 2 1 0 0 0
CITY 3 1 0 0 1
CITY 4 2 0 1 0
1. 1. A(:,2)
2. A(1:2:3,:)
3. A(:,1:2) = []
4. A = [A [7; 8; 9]]
2. 1. A+B = [6 4 6; 10 9 10]
2. A*3 = [6 0 6; 3 0 3]
3. A.*3 = [6 0 6; 3 0 3]
4. A.^3 = [8 0 8; 1 0 1]
5. (A + B)./B = [1.500 1.000 1.500;
1.1111 1.0000 1.1111]
6. (A + B)./A = Warning: Divide by zero.
[ 3 Inf 3
10 Inf 10]
3. 1. A*B = 60
2. A*C = ??? Error using ==> *
Inner matrix dimensions must agree.
3. B*C = [ 8 48 0 0
-24 -144 0 0
8 48 0 0
-24 -144 0 0]
4. C*B = -136
280 Arrays and Matrix Operations
Problems
5. A*B = [ 24 144; 6 36 ]
6. B*A = [ 60 -52; 0 0 ]
4. 1. A' = [ 2 1; 0 –5 ]
2. det(A) = -10
3. B' = [ 3 4 0
-2 1 -3
0 5 4 ]
4. det(B) = 89
5. A^2 = [ 4 0; -3 25 ]
6. inv(A) = [ 0.5000 0; 0.1000 -0.2000 ]
7. inv(B) = [ 0.2135 0.0899 -0.1124
-0.1798 0.1348 -0.1685
-0.1348 0.1011 0.1236]
8. A^-2 = [ 0.2500 0; 0.0300 0.0400 ]
5. 1. sort(A)
2. mean(A)
3. median(A)
4. mean(mean(A))
5. sort(A,2)
6. mean(A,2)
7. median(A,2)
8. mean(mean(A,2))
Problems
Section 1.
What is the order and main diagonal of the following matrices?
1. [3, 4; 5, 6; 7, 8]
2. [2 3 4 5; 6 7 8 9]
3. [2 1 0; 2 -3 1; 4 0 0; 3 2 1]
Verify your answers by using appropriate MATLAB functions.
Section 2.
4. Create a vector A that contains the following fractions:
>> A
A =
1/2 2/3 3/4 4/5 5/6
What command changes your format so the vector displays rational fractions in-
stead of decimals?
5. What command creates a 4 * 5 matrix that contains all zeros?
Section 3.
6. The loads in kilograms on the center points of five beams are
400.3
521.1
Arrays and Matrix Operations 281
Arrays and Matrix Operations
212.1
349.5
322.2
Create a row vector named “Loads” that contains the five values. What is a
single command that replaces the second and fourth values of “Loads” with
zero? What is a single command that deletes the third and fifth elements of
“Loads”?
7. Re-create the original row vector “Loads” from the previous problem. The
lengths in meters of the five beams are, respectively,
14.3
6.2
22.6
2.4
10.2
Create a row vector named “Lengths” that contains the five beam lengths in
meters. In a single command, create a matrix named “Beams” by concatenating
“Loads” and “Lengths”. “Beams” should have two rows with the load values on
the first row and the respective lengths on the second row. Your answer should
look like the following:
>> Beams =
400.3000 521.1000 212.1000 349.5000 322.2000
14.3000 6.2000 22.6000 2.4000 10.2000
Section 4.
8. Assume that the loads for the five beams in Problem 6 are distributed evenly
across the length of each beam. Using array arithmetic, and the original vectors
“Loads” and “Lengths”, create a vector that represents the average load in kg/m
for each beam.
9. The command rand(1,n) produces a row vector of n uniformly distributed,
pseudorandom numbers between 0.0 and 1.0. Use array arithmetic and the
rand function to create 100 uniformly distributed pseudorandom numbers be-
tween 8.0 and 10.0.
Section 5.
10. Express the following linear system in matrix form as matrices A and B:
3x1 + 2x2 = 4
-5x1 + 10x2 = 0
11. Use the MATLAB left matrix division operator to find the solution of the linear
system in the previous problem.
Section 6.
12. The transpose of the transpose of a matrix equals the original matrix. This can
be stated as 1AT2T = A. Using MATLAB, demonstrate that the theorem is true
for the following matrix:
A = [1 2 4 6; 4 3 2 1].
282 Arrays and Matrix Operations
Problems
13. Experiment with the transpose operator on a few example matrices. What con-
clusion do you reach about the main diagonal of a matrix and the main diagonal
of its transpose?
14. Given a matrix representation of a system of linear equations AX = B, if the
determinant of A equals zero, the system does not have a unique solution.
Two possibilities are that the system has no solutions and that the system has
an infinite number of solutions. Determine if the following system has a
unique solution:
2x1 + 3x2 + 4x3 = 10
-x1 + 3x2 - x3 = 12
3
x1 + x2 + 2x3 = 0
2
15. The inverse of an array A multiplied by itself should equal the identity matrix of
the same order as A. Show how you would test this assumption. Use matrix
multiplication and the inv, eye, and size functions.
16. The following matrix represents the numbers of direct paths between four net-
work routers:
R1 R2 R3 R4
R1 0 2 1 3
R2 2 0 0 2
R3 1 0 0 2
R4 3 2 2 0
How many paths are there from router two to router four if each path passes
through exactly one other router?
Section 7.
17. Create a 2 * 4 * 3 array of random numbers. Replace the cell contents in the
third page of the array with zeros.
18. Create a three-dimensional array of order 6 * 2 * 3. Fill page one with 1’s,
page two with 2’s, and page 3 with 3’s. Can you solve the problem in a single
command?
Section 8.
19. Create the following array:
Reshape A into a two-column array. What is the bottom number in each column?
Challenge Problem
20. Reread Programming Tip 1. Test the assertion in the tip by writing a program
that creates a 1 * 20000 row vector of ones in a single command. Write anoth-
er program that creates a 1 * 1 row vector and then builds a 1 * 20000 vector
of ones a single cell at a time using a loop.
Time both programs and compare the efficiency of the two methods. Hints:
The function clock returns a six-element vector containing the current date and
time. The meaning of each element in the vector is [year, month, day, hour,
minute, seconds].
Arrays and Matrix Operations 283
Arrays and Matrix Operations
The elapsed time function, etime(t2, t1), returns the elapsed time in seconds
between time t2 and time t1. The following code segment computes the time
taken to execute the code between t1 and t2:
t1 = clock
...
...
t2 = clock
ElapsedTime = etime(t2,t1)