0

# More About Matrices and Arrays

**Generating Matrices**MATLAB software provides four functions that generate basic matrices.

zeros All zeros

ones All ones

rand Uniformly distributed random elements

randn Normally distributed random elements

Here are some examples:

Z = zeros(2,4)

Z =

0 0 0 0

0 0 0 0

F = 5*ones(3,3)

F =

5 5 5

5 5 5

5 5 5

N = fix(10*rand(1,10))

N =

9 2 6 4 8 7 4 0 8 4

R = randn(4,4)

R =

0.6353 0.0860 -0.3210 -1.2316

-0.6014 -2.0046 1.2366 1.0556

0.5512 -0.4931 -0.6313 -0.1132

-1.0998 0.4620 -2.3252 0.3792

**The load Function**The load function reads binary files containing matrices generated by earlier

MATLAB sessions, or reads text files containing numeric data. The text file

should be organized as a rectangular table of numbers, separated by blanks,

with one row per line, and an equal number of elements in each row. For

example, outside of MATLAB, create a text file containing these four lines:

16.0 3.0 2.0 13.0

5.0 10.0 11.0 8.0

9.0 6.0 7.0 12.0

4.0 15.0 14.0 1.0

Save the file as magik.dat in the current directory. The statement

load magik.dat

reads the file and creates a variable, magik, containing the example matrix.

An easy way to read data into MATLAB from many text or binary formats

is to use the Import Wizard.

Saving Code to a File

You can create matrices using text files containing MATLAB code. Use the

MATLAB Editor or another text editor to create a file containing the same

statements you would type at the MATLAB command line. Save the file

under a name that ends in .m.

For example, create a file in the current directory named magik.m containing

these five lines:

A = [16.0 3.0 2.0 13.0

5.0 10.0 11.0 8.0

9.0 6.0 7.0 12.0

4.0 15.0 14.0 1.0 ];

The statement

magik

reads the file and creates a variable, A, containing the example matrix.

Concatenation

Concatenation is the process of joining small matrices to make bigger ones. In

fact, you made your first matrix by concatenating its individual elements. The

pair of square brackets, [], is the concatenation operator. For an example,

start with the 4-by-4 magic square, A, and form

B = [A A+32; A+48 A+16]

The result is an 8-by-8 matrix, obtained by joining the four submatrices:

B =

16 3 2 13 48 35 34 45

5 10 11 8 37 42 43 40

9 6 7 12 41 38 39 44

4 15 14 1 36 47 46 33

64 51 50 61 32 19 18 29

53 58 59 56 21 26 27 24

57 54 55 60 25 22 23 28

52 63 62 49 20 31 30 17

This matrix is halfway to being another magic square. Its elements are a

rearrangement of the integers 1:64. Its column sums are the correct value

for an 8-by-8 magic square:

sum(B)

ans =

260 260 260 260 260 260 260 260

But its row sums, sum(B')', are not all the same. Further manipulation is

necessary to make this a valid 8-by-8 magic square.

Deleting Rows and Columns

You can delete rows and columns from a matrix using just a pair of square

brackets. Start with

X = A;

Then, to delete the second column of X, use

X(:,2) = []

This changes X to

X =

16 2 13

5 11 8

9 7 12

4 14 1

If you delete a single element from a matrix, the result is not a matrix

anymore. So, expressions like

X(1,2) = []

result in an error. However, using a single subscript deletes a single element,

or sequence of elements, and reshapes the remaining elements into a row

vector. So

X(2:2:10) = []

results in

X =

16 9 2 7 13 12 1

Linear Algebra

Informally, the terms matrix and array are often used interchangeably. More

precisely, a matrix is a two-dimensional numeric array that represents a

linear transformation. The mathematical operations defined on matrices are

the subject of linear algebra.

Dürer’s magic square

A = [16 3 2 13

5 10 11 8

9 6 7 12

4 15 14 1]

provides several examples that give a taste of MATLAB matrix operations.

You have already seen the matrix transpose, A'. Adding a matrix to its

transpose produces a symmetric matrix:

A + A'

ans =

32 8 11 17

8 20 17 23

11 17 14 26

17 23 26 2

The multiplication symbol, *, denotes the matrix multiplication involving

inner products between rows and columns. Multiplying the transpose of a

matrix by the original matrix also produces a symmetric matrix:

A'*A

ans =

378 212 206 360

212 370 368 206

206 368 370 212

360 206 212 378

The determinant of this particular matrix happens to be zero, indicating

that the matrix is singular:

d = det(A)

d =

0

The reduced row echelon form of A is not the identity:

R = rref(A)

R =

1 0 0 1

0 1 0 -3

0 0 1 3

0 0 0 0

Because the matrix is singular, it does not have an inverse. If you try to

compute the inverse with

X = inv(A)

you will get a warning message:

Warning: Matrix is close to singular or badly scaled.

Results may be inaccurate. RCOND = 9.796086e-018.

Roundoff error has prevented the matrix inversion algorithm from detecting

exact singularity. But the value of rcond, which stands for reciprocal

condition estimate, is on the order of eps, the floating-point relative precision,

so the computed inverse is unlikely to be of much use.

The eigenvalues of the magic square are interesting:

e = eig(A)

e =

34.0000

8.0000

0.0000

-8.0000

One of the eigenvalues is zero, which is another consequence of singularity.

The largest eigenvalue is 34, the magic sum. That sum results because the

vector of all ones is an eigenvector:

v = ones(4,1)

v =

1

1

1

1

A*v

ans =

34

34

34

34

When a magic square is scaled by its magic sum,

P = A/34

the result is a doubly stochastic matrix whose row and column sums are all 1:

P =

0.4706 0.0882 0.0588 0.3824

0.1471 0.2941 0.3235 0.2353

0.2647 0.1765 0.2059 0.3529

0.1176 0.4412 0.4118 0.0294

Such matrices represent the transition probabilities in a Markov process.

Repeated powers of the matrix represent repeated steps of the process. For

this example, the fifth power

P^5

is

0.2507 0.2495 0.2494 0.2504

0.2497 0.2501 0.2502 0.2500

0.2500 0.2498 0.2499 0.2503

0.2496 0.2506 0.2505 0.2493

This shows that as k approaches infinity, all the elements in the k th power,p^k approach 1/4

Finally, the coefficients in the characteristic polynomial

poly(A)

are

1 -34 -64 2176 0

These coefficients indicate that the characteristic polynomial is

The constant term is zero because the matrix is singular. The coefficient of

the cubic term is -34 because the matrix is magic!

**Arrays**When they are taken away from the world of linear algebra, matrices become

two-dimensional numeric arrays. Arithmetic operations on arrays are

done element by element. This means that addition and subtraction are

the same for arrays and matrices, but that multiplicative operations are

different. MATLAB uses a dot, or decimal point, as part of the notation for

multiplicative array operations.

The list of operators includes

+ Addition

- Subtraction

.* Element-by-element multiplication

./ Element-by-element division

.\ Element-by-element left division

.^ Element-by-element power

.' Unconjugated array transpose

If the Dürer magic square is multiplied by itself with array multiplication

A.*A

the result is an array containing the squares of the integers from 1 to 16,

in an unusual order:

ans =

256 9 4 169

25 100 121 64

81 36 49 144

16 225 196 1

Building Tables

Array operations are useful for building tables. Suppose n is the column vector

n = (0:9)';

Then

pows = [n n.^2 2.^n]

builds a table of squares and powers of 2:

pows =

0 0 1

1 1 2

2 4 4

3 9 8

4 16 16

5 25 32

6 36 64

7 49 128

8 64 256

9 81 512

The elementary math functions operate on arrays element by element. So

format short g

x = (1:0.1:2)';

logs = [x log10(x)]

builds a table of logarithms.

logs =

1.0 0

1.1 0.04139

1.2 0.07918

1.3 0.11394

1.4 0.14613

1.5 0.17609

1.6 0.20412

1.7 0.23045

1.8 0.25527

1.9 0.27875

2.0 0.30103

**Multivariate Data**MATLAB uses column-oriented analysis for multivariate statistical data.

Each column in a data set represents a variable and each row an observation.

The (i,j)th element is the ith observation of the jth variable.

As an example, consider a data set with three variables:

• Heart rate

• Weight

• Hours of exercise per week

For five observations, the resulting array might look like

D = [ 72 134 3.2

81 201 3.5

69 156 7.1

82 148 2.4

75 170 1.2 ]

The first row contains the heart rate, weight, and exercise hours for patient 1,

the second row contains the data for patient 2, and so on. Now you can apply

many MATLAB data analysis functions to this data set. For example, to

obtain the mean and standard deviation of each column, use

mu = mean(D), sigma = std(D)

mu =

75.8 161.8 3.48

sigma =

5.6303 25.499 2.2107

For a list of the data analysis functions available in MATLAB, type

help datafun

If you have access to the Statistics Toolbox™ software, type

help stats

Scalar Expansion

Matrices and scalars can be combined in several different ways. For example,

a scalar is subtracted from a matrix by subtracting it from each element. The

average value of the elements in our magic square is 8.5, so

B = A - 8.5

forms a matrix whose column sums are zero:

B =

7.5 -5.5 -6.5 4.5

-3.5 1.5 2.5 -0.5

0.5 -2.5 -1.5 3.5

-4.5 6.5 5.5 -7.5

sum(B)

ans =

0 0 0 0

With scalar expansion, MATLAB assigns a specified scalar to all indices in a

range. For example,

B(1:2,2:3) = 0

zeroes out a portion of B:

B =

7.5 0 0 4.5

-3.5 0 0 -0.5

0.5 -2.5 -1.5 3.5

-4.5 6.5 5.5 -7.5

**Logical Subscripting**The logical vectors created from logical and relational operations can be used

to reference subarrays. Suppose X is an ordinary matrix and L is a matrix of

the same size that is the result of some logical operation. Then X(L) specifies

the elements of X where the elements of L are nonzero.This kind of subscripting can be done in one step by specifying the logical

operation as the subscripting expression. Suppose you have the following

set of data:

x = [2.1 1.7 1.6 1.5 NaN 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8];

The NaN is a marker for a missing observation, such as a failure to respond to

an item on a questionnaire. To remove the missing data with logical indexing,

use isfinite(x), which is true for all finite numerical values and false for

NaN and Inf:

x = x(isfinite(x))

x =

2.1 1.7 1.6 1.5 1.9 1.8 1.5 5.1 1.8 1.4 2.2 1.6 1.8

Now there is one observation, 5.1, which seems to be very different from the

others. It is an outlier. The following statement removes outliers, in this case

those elements more than three standard deviations from the mean:

x = x(abs(x-mean(x)) <= 3*std(x))

x =

2.1 1.7 1.6 1.5 1.9 1.8 1.5 1.8 1.4 2.2 1.6 1.8

For another example, highlight the location of the prime numbers in Dürer’s

magic square by using logical indexing and scalar expansion to set the

nonprimes to 0.

A(~isprime(A)) = 0

A =

0 3 2 13

5 0 11 0

0 0 7 0

0 0 0 0

The find Function

The find function determines the indices of array elements that meet a given

logical condition. In its simplest form, find returns a column vector of indices.

Transpose that vector to obtain a row vector of indices. For example, start with Dürer’s magic square.

k = find(isprime(A))'

picks out the locations, using one-dimensional indexing, of the primes in the

magic square:

k =

2 5 9 10 11 13

Display those primes, as a row vector in the order determined by k, with

A(k)

ans =

5 3 2 11 7 13

When you use k as a left-hand-side index in an assignment statement, the

matrix structure is preserved:

A(k) = NaN

A =

16 NaN NaN NaN

NaN 10 NaN 8

9 6 NaN 12

4 15 14 1

## Post a Comment