Matlab Matrix Operations

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

9

Arrays and Matrix Operations

1 THE PRIMARY MATLAB DATA Section


STRUCTURE
1 The Primary MATLAB Data Structure
As we have previously stated, the basic data element in the 2 Entering Arrays and Matrices
MATLAB system is the array. A scalar is represented as a 3 Accessing and Manipulation Array
1 * 1 array—that is, an array with one row and one column. Elements
Vectors are one-dimensional arrays. An m * 1 array is 4 Element-by-Element Array
called a column vector, where m is the number of rows in Operations
the single-column array. A 1 * n array is called a row vec- 5 Binary Matrix Operations
tor, where n is the number of columns in the single-row 6 Unary Matrix Operations
array. Array elements may be numbers, characters, strings, 7 Multidimensional Array
other arrays, or structures. Recall that the elements in an 8 Useful Array Functions
array must be uniform. A special type of array, called a cell
array, allows nonuniform elements.
MATLAB supports multidimensional arrays. A matrix Objectives
is a special case of an array. A matrix is a rectangular array
containing elements of any specified algebraic system, usu- After reading this chapter, you should be
ally real or complex numbers. The English mathematician able to
Arthur Cayley first introduced the concept of a matrix in the • Create arrays and matrices.
mid-19th century. Matrices are employed to help solve sys- • Access elements in arrays and matrices.
tems of linear equations and to perform linear transforma-
• Add, modify, and delete elements from
tions. This chapter describes several applications of matrix
arrays.
algebra to scientific and engineering problems.
MATLAB arrays are, by default, self-dimensioning. • Perform element-by-element arithmetic
That is, if we initialize an array with a set of values, MAT- operations on arrays.
LAB automatically allocates the correct amount of space for • Perform vector and matrix
the array. If you append an element to an array, MATLAB multiplication.
automatically resizes the array to handle the new element. • Perform matrix exponentiation.
This is different from many programming languages, where • Compute the transpose, determinant,
memory allocation and array sizing takes a considerable and inverse of a matrix.
amount of programming effort.

From MATLAB® Programming, David C. Kuncicky. Copyright © 2004 by Pearson Education, Inc. All rights reserved.
Arrays and Matrix Operations 255
Arrays and Matrix Operations

Matrix A consisting of m rows and n columns is said to be of order m * n. If


m = n, then matrix A is called a square matrix. The following matrix A is a square ma-
trix of order three:
2 4 6
A = C3 5 7S
1 2 3
Recall that you can reference the cells in a matrix by subscripts, representing the row
number and column number, respectively. Thus, A12,32 = 7. We call the collection of
cells in a matrix for which the row numbers equal the column numbers the main diago-
nal. The main diagonal of A is [2, 5, 3].

2 ENTERING ARRAYS AND MATRICES

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.

2.1 Command Line Entry


Let us review how to enter arrays in the Command window. The syntax includes brack-
ets for the whole array and delimiters for rows and columns. Elements in the same row
are separated by commas or spaces. A new row is created by using a semicolon or a new
line. The whole array is bracketed by square braces. The array
1 3 5
C2 4 6S
7 7 7
is entered as
>> [1, 3, 5; 2, 4, 6; 7, 7, 7]
ans =
1 3 5
2 4 6
7 7 7
You can also create the same array by using spaces to separate the elements in the same
row instead of commas:
>> [1 3 5; 2 4 6; 7 7 7];
You can also create the same array by moving to a new line every time you designate a
new row:
>> [1 3 5
2 4 6
7 7 7]
Note that the continuation symbol 1 Á 2 is not required.
Moreover, you can enter array elements in series more concisely by using the
colon operator.
256 Arrays and Matrix Operations
Entering Arrays and Matrices

2.2 The Array Editor


The Array Editor is a graphical interface that displays the contents of workspace objects
and allows you to edit them. If the Workspace window is not visible, select
View : Workspace from the Menu bar. Enter the following command in the Com-
mand window:
>> A = 5 : 0.5 : 7
A =
5.0000 5.5000 6.0000 6.5000 7.0000
The workspace contents will now include a 1 * 5 array named A as depicted in
Figure 1.

Figure 1. The Workspace window.

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.

Figure 2. The Array Editor.

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

TABLE 1. Numeric Formats.


Type Format Precision
short fixed point, scaled 5 digits
short e floating point 5 digits
short g fixed or floating point as many significant
(most accurate) figures as possible
with 5 digits
long fixed point, scaled 15 digits
long e floating point 15 digits
long g fixed or floating point as many significant
(most accurate) figures as possible
with 15 digits
rat rational expression approximates a
rational fraction
hex hexadecimal base 16

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)

2.4 Built-In Matrix Generators


We use several types of arrays so frequently that MATLAB has provided special func-
tions to support the generation of these arrays. We call a matrix in which all of the ele-
ments are zero a zero matrix. You can create a zero array or matrix by using the zeros
function. The syntax of the zeros function is
zeros(dim1, dim2, dim3, ...)
If you specify a single, scalar parameter dim1, MATLAB returns a square zero matrix of
order dim1. For example, the following command creates a 2 * 2 matrix of zeros:
>>A = zeros(2)
A =
0 0
0 0
If you specify multiple parameters, a multidimensional zero array of order dim1 *
dim2 * dim3 Á is returned. The following command creates a 2 * 4 matrix of
zeros:
>> A = zeros(2, 4)
A =
0 0 0 0
0 0 0 0
Arrays and Matrix Operations 259
Arrays and Matrix Operations

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

3 ACCESSING AND MANIPULATING ARRAY ELEMENTS

3.1 Accessing Elements of an Array


You have already accessed array elements by using subscripts. Let us review what you
have learned and cover a few more tricks for accessing array elements. We will use the
following two-dimensional array A for the next few examples:
>> A = [1 3 5; 2 4 6; 3 5 7]
A =
1 3 5
2 4 6
3 5 7
An element in a two-dimensional array can be accessed by using two subscripts, the first
for the row and the second for the column; for example,
>> A(2,3)
ans =
6
You can also access elements in a two-dimensional array by using a single subscript. In
this case, imagine the columns lay end to end as follows:
A = [ 1
2
3
3
4
5
5
6
7 ]
This makes more sense if we look at how MATLAB stores arrays internally. Data are
stored internally in a linear sequence of memory locations. MATLAB stretches out an
array into a single sequence for storage.
We think of array A as a two-dimensional array. If A were stored one row at a time
in memory, it might look like this:
1 3 5 2 4 6 3 5 7
This is called row-major order. However, if A were stored one column at a time in mem-
ory, it would look like the following:
1 2 3 3 4 5 5 6 7
This is called column-major order. MATLAB stores arrays in column-major order. MAT-
LAB functions are written to take advantage of the underlying storage mechanism to
speed up array operations.
The following examples demonstrate how to access an array element by using a
single subscript:
>> A(1)
ans =
1
>> A(4)
Arrays and Matrix Operations 261
Arrays and Matrix Operations

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

3.2 Expanding the Size of an Array


You can dynamically expand an array simply by adding more elements—for example,
>> A = [3 5 7]
A =
3 5 7
>> A = [A 9]
A =
3 5 7 9
When appending arrays to multidimensional arrays, the newly appended parts must con-
form to the dimensions of the original array. For example, if adding a new row to a two-
dimensional array, the row must have the same number of columns as the original array:
>> A = [3 5 7];
>> B = [1 3 5];
>> C = [A; B]
C =
3 5 7
1 3 5
If you try to append to an array and the appended part does not conform dimensionally,
an error will result. Here’s an example:
>> A = [3 5 7];
>> B = [2 4];
262 Arrays and Matrix Operations
Accessing and Manipulating Array Elements

>> 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

3.3 Deleting Array Elements


You can delete array elements by replacing them with the empty array, which we desig-
nate as []. In the following example, the second element of vector A is removed:
>> A = [3 5 7];
>> A(2) = []
A =
3 7
You cannot remove a single element from a multidimensional array, since the array
would no longer be conformant. This results in an error, as shown in this example:
>> A = [1 3 5; 2 4 6]
A =
1 3 5
2 4 6
>> A(2,3) = []
??? Indexed empty matrix assignment is not allowed.
You can use the colon operator in deletion operations. The colon operator allows dele-
tion of whole rows or columns. In the next example, the second row of the 2 * 3 array
A is removed:
>> A = [1 3 5; 2 4 6]
A =
1 3 5
2 4 6
>> A(2,:) = []
A =
1 3 5
The following example removes the first, third, and fifth columns from array A:
>> 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
Arrays and Matrix Operations 263
Arrays and Matrix Operations

>> A(:, 1:2:5) = []


A =
2 4 6
8 10 12

PRACTICE 1! Let array

>> 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:

1. Return the second column of A.


2. Return the first and third rows of A.
3. Delete the first and second columns of A.
4. Append the column vector [7; 8; 9] to A.

Re-create array A again before each problem. Check your answers by using MATLAB.

4 ELEMENT-BY-ELEMENT ARRAY OPERATIONS

4.1 Array Addition


MATLAB performs addition or subtraction of two arrays of the same order by adding or
subtracting each pair of respective elements. The result is an array of the same order.
For example, given that
A = [1 3 5] and B = [10 12 14]
A + B is calculated as follows:
[A112 + B112 A122 + B122 A132 + B132] = [11 15 19].
Here is another example, this time we are using two-dimensional arrays. Given that
1 3 5
A = C2 4 6S
7 7 7
and
-5 6 14
B = C 0 -2 4 S
2 8 3
the sum of A and B is
-4 9 19
A + B = C 2 2 10 S
9 15 10
If two arrays are not of the same order, we say they are not conformable for addition or
subtraction. For example, the following matrices C and D are not conformable for addi-
tion or subtraction because C’s dimensions are 1 * 3 and D’s dimensions are 2 * 3:
264 Arrays and Matrix Operations
Element-by-Element Array Operations

>> 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.

4.2 Array Multiplication


MATLAB performs array multiplication by multiplying each pair of respective elements
in two arrays of the same order. The symbol for array multiplication is a period followed
by an asterisk 1.*2. The following example demonstrates array multiplication:
>> A = [1, 3, 5; 2, 4, 6]
A =
1 3 5
2 4 6
>> B = [2, 3, 4; -1, -2, -3]
B =
2 3 4
-1 -2 -3
>> A .* B
ans =
2 9 20
-2 -8 -18
To be conformable for array multiplication, the two arrays must be of the same order,
unless one array is a scalar, in which case, each element of the other array is multiplied
by the scalar—for example,
>> A = [5]
A =
5
>> B = [2, 4, 6]
B =
2 4 6
>> A .* B
ans =
10 20 30
Arrays and Matrix Operations 265
Arrays and Matrix Operations

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

4.3 Array Right Division


MATLAB performs array right division of arrays A and B by dividing each element in
array A by the respective element in array B. The symbol for array right division is a pe-
riod followed by a forward slash (./). To be conformable for array right division, the two
arrays must be of the same order, unless one array is a scalar. The following example
demonstrates array right division:
>> A = [2, 4, 6]
A =
2 4 6
>> B = [2, 2, 2]
B =
2 2 2
>> A./B
ans =
1 2 3

4.4 Array Left Division


MATLAB performs array left division of arrays A and B by dividing each element in
array B by the respective element in array A. The symbol for array left division is a peri-
od followed by a back slash (.\). To be conformable for array left division, the two arrays
must be of the same order, unless one array is a scalar. The following example demon-
strates array left division, using the arrays A and B from the previous example:
>> A.\B
ans =
1.0000 0.5000 0.3333

4.5 Array Exponentiation


MATLAB performs array exponentiation of arrays A and B by raising each element in
array A to the power of its respective element in array B. The symbol for array exponen-
tiation is a period followed by the caret symbol 1.¿2. To be conformable for array expo-
nentiation, the two arrays must be of the same order, unless one array is a scalar. The
following example demonstrates array exponentiation:
>> A = [2, 3, 4]
A =
2 3 4
>> B = [3, 2, 0.5]
B =
3.0000 2.0000 0.5000
266 Arrays and Matrix Operations
Binary Matrix Operations

>> 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.

5 BINARY MATRIX OPERATIONS

A binary operation is a mathematical computation performed by using two matrices as


inputs. Binary matrix operations are not as straightforward to compute as element-by-
element operations. Binary matrix operations have many applications, such as the solu-
tion of systems of linear equations.

5.1 Vector Multiplication


We will first describe vector multiplication mathematically and then show you how to
perform the operation by using MATLAB. Two vectors a and b are multiplied by com-
puting their dot product. The dot product, sometimes called the inner product, is calcu-
lated by adding the products of each pair of respective elements in vectors a and b. To
be conformable for vector multiplication a must be a row vector and b must be a col-
umn vector. In addition, the vectors must contain the same number of elements, unless
one is a scalar. If row vector
a = [a1 a2 Á an],

and column vector


b1
b2
b = D T
Á
bn

the dot product

a # b = a1b1 + a2b2 + Á + anbn.


Arrays and Matrix Operations 267
Arrays and Matrix Operations

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.

5.2 Matrix Multiplication


MATLAB performs the multiplication of matrix A by a scalar by multiplying each ele-
ment of A by the scalar. Any array or matrix can be multiplied by a scalar. The following
is an example:
A = [1, 3; -2, 0]
A =
1 3
-2 0
B = A * 5
B =
5 15
-10 0
MATLAB performs multiplication of nonscalar A and B by computing the dot products
of each row in A with each column in B. Each result becomes a row in the resulting ma-
trix. We will try to make this clearer by walking through an example:
>> A = [1 3 5; 2 4 6]
A =
1 3 5
2 4 6
268 Arrays and Matrix Operations
Binary Matrix Operations

>> B = [-2 4; 3 8; 12 -2]


B =
-2 4
3 8
12 -2
Note that the number of rows in A1mA = 22 equals the number of columns in
B1nB = 22. To be conformable for matrix multiplication, the number of rows in A must
equal the number of columns in B. The result will be an mA * nB matrix. In the exam-
ple, the result will be a 2 * 2 matrix.
The first step is to compute the dot product of row one of A and column one of B:
(1 * -2) + (3 * 3) + (5 * 12)= 67
Place the result in cell (1, 1) of the result matrix. Next, compute the dot product of row
one of A and column two of B:
(1 * 4) + (3 * 8) + (5 * -2)= 18
Place the result in cell (1, 2) of the result matrix. Next, compute the dot product of row
two of A and column one of B:
(2 * -2) + (4 * 3) + (6 * 12)= 80
Place the result in cell (2, 1) of the result matrix. Finally, compute the dot product of row
two of A and column two of B:
(2 * 4) + (4 * 8) + (6 * -2)= 28
Place the result in cell (2, 2) of the result matrix. The resulting product is
>> A*B
ans =
67 18
80 28
For most cases of A and B, matrix multiplication is not commutative; that is,
AB Z BA.

5.3 Matrix Division


The operations for left and right matrix division are not straightforward. We will not walk
through the underlying algorithm for their computation in this text. However, we will
show you an application of the left matrix division operator.
A common and useful application of matrices is the representation of systems of
linear equations. The linear system

3x1 + 2x2 + x3 = 5
x1 + 2x2 + 3x3 = 13
-5x1 - 10x2 - 5x3 = 0

can be represented compactly as the matrix product AX = B:

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.

PRACTICE 3! Given vectors


A = [ 2 –3 4 0]
B = [ 4; -12; 4; -12]
C = [ 2 12 0 0]
compute the following operations by hand and then check your answers by using
MATLAB:
1. A * B
2. A * C
3. B * C
4. C * B
Given the matrices
A = [ 12 4; 3 –5]
B = [ 2 12; 0 0]
compute the following operations by hand and then check your answers by using
MATLAB:
5. A * B
6. B * A

6 UNARY MATRIX OPERATIONS

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

the transpose of A, denoted in mathematics as AT, is

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:

d = a11 # a22 - a21 # a12


a11 a12
detc
a21 a22
MATLAB has a function that computes the determinant named det. The syntax for the
det function is

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.

In our example, the cofactor of a12 is


A12 = 1-121 + 2 114 # 92 - 16 # 722 = 6.

The general form for the calculation of a determinant is


det A = ai1 Ai1 + ai2 Ai2 + Á + ain Ain
where i is any row in square matrix A of order n. The answer is the same no matter which
row is chosen. A similar formula works by choosing any column in A. Let us follow the
example and expand A around row 2:

det A = 4 # 1-122 + 1 # det c d + 5 # 1-122 + 2 # det c d


2 3 1 3
8 9 7 9

+ 6 # 1-122 + 3 # detc d
1 2
7 8
= 1-4 # -62 + 15 # -122 + 1-6 # -62
= 0.

We find that by using MATLAB to compute the determinant of A results in


A =
1 2 3
4 5 6
7 8 9
>> det(A)
ans =
0
As you can see, the determinant of a high order matrix is tedious to calculate by hand.
Moreover, because the calculation of a higher order determinant is computationally in-
tensive and involves a series of recursive steps, the rounding error can be significant.
6.3 Inverse
The inverse of a square matrix A, if it exists, is defined to be a square matrix such that
AA-1 = I,
where I is the identity matrix of the same order as A. The matrix inverse operation is de-
noted mathematically by using a negative one exponent, A-1.
272 Arrays and Matrix Operations
Unary Matrix Operations

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

6.4 Matrix Exponentiation


MATLAB computes the positive integer power of a square matrix A by multiplying A
times itself the requisite number of times. The multiplication operation that is per-
formed is matrix multiplication, not element-by-element multiplication—for example,
>> A = [1, 2; 3, 4]
A =
1 2
3 4
>> A^2
ans =
7 10
15 22
>> A^3
ans =
37 54
81 118
The negative integer power of a square matrix A is computed by performing matrix mul-
tiplication of the inverse of A the requisite number of times. For example, to compute
the second negative root of A, we type
Arrays and Matrix Operations 273
Arrays and Matrix Operations

>> 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

PRACTICE 4! Given the square matrices


A = [ 2 0; 1 -5]
B = [ 3 –2 0; 4 1 5; 0 –3 4]
compute the following operations by hand and then check your answers by using
MATLAB:
1. A'
2. det(A)
3. B'
4. det(B)
Compute the following with MATLAB:
5. A^2
6. inv(A)
7. inv(B)
8. A^-2

7 MULTIDIMENSIONAL ARRAYS

We have previously used examples of two-dimensional arrays. Many of MATLAB’s array


operations can be extended to more than two dimensions.
The following command creates a three-dimensional array of order 2 * 3 * 2.
Since MATLAB cannot display the whole array at once, it displays the array a page at a
time. There are two pages in the following example, as the third dimension takes two levels:
>> A = ones(2,3,2)
A(:,:,1) =
1 1 1
1 1 1
274 Arrays and Matrix Operations
Useful Array Functions

A(:,:,2) =
1 1 1
1 1 1

8 USEFUL ARRAY FUNCTIONS

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

max, min, mean, median


The max, min, mean, and median functions each work in a similar fashion to the sort
function. Given a vector argument, the functions return the maximum, minimum, mean,
or median value, respectively. If given a two-dimensional array, each function returns a
vector that contains the result of the operation on each column.
Because these functions each work in a similar fashion, we will demonstrate their
use with the min function. First, we will use a vector as an example:
>> A = [ 3 2 -6 1 10];
>> min(A)
ans =
-6
Next, we will show an example that uses a two-dimensional array:
>> A = [ 2 1 3; 4 2 2; 5 0 -2]
A =
2 1 3
4 2 2
5 0 -2
>> min(A)
ans =
2 0 -2
Note that min returns the minimum for each column.

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

APPLICATION! COMMUNICATION ROUTES

The calculation of the number of communication paths A =


is important in a variety of fields, for example, the con- 0 1 1 2
trol of network router traffic. Scientists use the same 1 0 0 0
theory to model behavior in fields such as human com-
1 0 0 1
munication, political influence, and the flow of money
through organizations. 2 0 1 0
A common example, used to demonstrate princi- Note that A is symmetric. This means that the cells
ples of communication routes, is the number of roads above the main diagonal are a mirror image of the cells
connecting cities. In this diagram we depict four cities below the diagonal when reflected along the diagonal.
along with the roads connecting them: Symmetry is also defined as A1n, m2 = A1m, n2 for any
m and n.
It is known that the matrix A^2 represents the
e number of ways to travel between any two cities by
1 2
d passing through only one intermediate city.
a c
3 >> B = A^2
4
b
B =
6 0 2 1
Table 2 shows the number of direct routes between 0 1 1 2
each pair of cities. A direct route does not go through
2 1 2 2
any intermediate city. For example, there are two direct
routes between City 1 and City 4. The table expresses 1 2 2 5
this information redundantly. You can see the routes be- Matrix B summarizes the number routes between pairs
tween City 1 and City 4 by looking at either (row 1, col- of cities if the route contains one intermediate city: Note
umn 4) or (row 4, column 1). We have presented the the six ways to travel from City 1 back to City 1 by passing
data in such a manner, so that it can be stored in a through exactly one other city: a–a, c–c, c–d, d–c, d–d,
square matrix. and e–e. The two ways to travel from City 2 to City 4 by
The square matrix A summarizes the connectivi- passing through exactly one other city are e–c and e–d.
ty between the cities. For example, A11,42 = 2 indi- We count traveling in one direction differently than
cates that there are two direct routes from City 1 to traveling the same route in the opposite direction. Thus,
City 4: there are two routes from City 1 to City 4, c–d and d–c.

TABLE 2. Number of routes among four cities.


City 1 City 2 City 3 City 4

CITY 1 0 1 1 2
CITY 2 1 0 0 0
CITY 3 1 0 0 1
CITY 4 2 0 1 0

KEY TERMS cofactor determinant main diagonal


colon operator dot product matrix
column-major order functional form minor
column vector identity matrix ones matrix
command form inner product order
compact format inverse row-major order
conformable loose format row vector
Arrays and Matrix Operations 279
Arrays and Matrix Operations

short format square matrix zero matrix


singleton dimension transpose
singularity zero diagonal

NEW MATLAB FUNCTIONS, COMMANDS, AND RESERVED WORDS

clock—returns current date and time


det—returns the determinant of a square matrix
diag—returns the diagonal of a matrix
etime—returns time elapsed between 2 times
eye—returns identity matrix
format—formats numeric output
get—returns the named properties of an object
inv—returns the inverse of a square matrix
length—returns the number of elements in a vector
max—returns the maximum element(s) along the first non-singleton dimension
mean—returns the mean element(s) along the first non-singleton dimension
median—returns the median element(s) along the first non-singleton dimension
min—returns the minimum element(s) along the first non-singleton dimension
ndims—returns the number of dimensions of an array
ones—returns an array of ones
rand—returns uniformly distributes pseudo-random numbers in [0,1]
reshape—reshapes an array
size—returns the order (size) of an array
sort—sorts an array in ascending order
zeros—creates an array of zeros

SOLUTIONS TO PRACTICE PROBLEMS

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:

A = [1:10; 11:20; 21:30].

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)

You might also like