﻿ Embracing Vectors, Matrices, and Higher Dimensions - MATLAB For Dummies, 2nd Edition

Part 2

# Manipulating and Plotting Data in MATLAB

IN THIS PART …

Defining the MATLAB memory structures

Manipulating data in memory

Chapter 5

# Embracing Vectors, Matrices, and Higher Dimensions

IN THIS CHAPTER Interacting with vectors and matrices Performing addition, subtraction, multiplication, and division Working with more than two dimensions Getting help with matrixes

The previous chapters of this book introduce you to MATLAB and its interface. Starting in this chapter, you become immersed in math a little more serious than 2 + 2. Of course, in this “more serious” math, many problems revolve around vectors and matrices, so these are good topics to start with. This chapter helps you understand how MATLAB views both vectors and matrices, and how to perform basic tasks with these structures. The chapter then takes you from two-dimensional matrices to matrices with three or more dimensions. All this material gives you a good idea of just how MATLAB can help you solve your vector and matrix problems.

Of course, you might still have questions. In fact, a single chapter of a book can’t answer every question on this topic. That’s why you also need to know how to obtain additional help. The last section of the chapter provides insights into how you can get additional matrix-oriented help from MATLAB and force it to do more of your matrix work for you. (After all, MATLAB is there to serve your needs, not the other way around.)

Working with Vectors and Matrices

A vector is simply a row of data elements. The length of this row has no limit and the values have no specific interval. A matrix is a two-dimensional table of data elements. Again, the size of this table has no limit (either in rows or columns), and the numbers have no specific interval. Both structures are well understood by mathematicians and engineers. They are used extensively by MATLAB to perform tasks that might otherwise require the use of complex structures not understood by these groups, which would unnecessarily complicate MATLAB usage.

The following sections describe how MATLAB uses vectors and matrices to make creating programs easier and demonstrates some of the ways in which MATLAB uses them. (Note that this chapter’s discussion assumes that you’re coming to the table with a basic understanding of linear algebra. If you find that you need to brush up on this particular area, check out the “Locating linear algebra resources online” sidebar.)

Understanding MATLAB’s perspective of linear algebra

Linear algebra deals with vector spaces and linear mappings between those spaces. You use linear algebra when working with lines, planes, and subspaces and their intersections. When working with linear algebra, vectors are viewed as coordinates of points in space, and the algebra defines operations to perform on those points. MATLAB divides linear algebra into these major areas:

· Matrix analysis

· Matrix operations

· Matrix decomposition

· Matrix properties

· Linear equations

· Eigenvalues

· Singular values

· Matrix functions

· Logarithms

· Exponentials

· Factorization

LOCATING LINEAR ALGEBRA RESOURCES ONLINE

This chapter doesn’t furnish a tutorial on linear algebra. Of course, not everyone remembers that college course in linear algebra, and some things that you don’t use every day are likely to be a little hard to remember. With this in mind, you might want to locate a linear algebra tutorial to jog your memory. Many good sources of information about linear algebra are available online.

One of the more interesting places to get some information about linear algebra is the Khan Academy at https://www.khanacademy.org/math/linear-algebra. Most of the information is relayed through videos, so you get the benefit of a classroom-like presentation. The presentations are short, for the most part — usually shorter than ten minutes — so you can watch segments as time allows. In addition, you can pick and choose among the videos to watch.

If all you really want is a quick brush-up on linear algebra, you might not need something as time-consuming as what the Khan Academy provides. In that case, you might want to check out the linear algebra tutorial in four pages at https://minireference.com/blog/linear-algebra-tutorial/. A number of people using this resource complained that it went really fast. After reviewing it, I can report that the four pages are well done, but they really do assume that you need a light refresher and already know how to use linear algebra quite well.

A middle-ground tutorial is found on Kardi Teknomo’s Page at https://people.revoledu.com/kardi/tutorial/LinearAlgebra/index.html. The interesting thing about this tutorial is that it’s interactive. You get somewhat detailed text instruction and then get to try your new skills right there on the site. The act of reading the information and then practicing what you learn makes the information stick better.

The point is that you’re likely to find a tutorial that meets your specific needs. You just need to invest a few minutes in trying out the various tutorials until you find one that fits your particular learning style. Offering such diversity in a single chapter of a book simply isn’t possible, so that’s why the online resources are so important.

This chapter doesn’t cover absolutely every area, but you are exposed to enough linear algebra to perform most tasks effectively using MATLAB. As the book progresses, you see additional examples of how to make MATLAB perform tasks using linear algebra. Think of this chapter as a really good start toward the goal of making MATLAB perform linear algebra tasks for you at a level of speed and accuracy you couldn’t achieve otherwise.

Entering data

Chapter 3 shows you how to import data from a spreadsheet or another data source. Of course, that’s fine if you have a predefined data source. However, you’ll often need to create your own data, so knowing how to type it yourself is important.

Think about how you use data when working with math: The data appears as a list of numbers or text. MATLAB uses a similar viewpoint. It also works with lists of numbers and text that you create through various methods. The following sections describe how to enter data as lists by using assorted techniques.

Entering values inside square brackets

The left square bracket, [, starts a list of numbers or text. The right square bracket, ], ends a list. Each entry in a list is separated by a comma (,). To try this technique yourself, open MATLAB, type b=[5, 6] in the Command Window, and press Enter. You see

b =

5 6

The information is stored as a list of two numbers. Each number is treated as a separate value. Double-click b in the Workspace window and you see two separate entries, as shown in Figure 5-1. Notice that the Variables window shows b as a 1-x-2 list of doubles in which the entries flow horizontally. FIGURE 5-1: Typing comma-separated numbers in square brackets produces a list of numbers. You can type format compact and press Enter to save display space. If you want to clear space in the Command Window for typing additional commands, type clc and press Enter. When you get too many variables in the Workspace window, type clear all and press Enter. Chapter 3 provides additional details on configuring MATLAB output.

Starting a new line or row with the semicolon

The comma creates separate entries in the same row. You use the semicolon (;) to produce new rows. To try this technique yourself, type e=[5; 6] in the Command Window and press Enter. You see

e =

5

6

As in the previous section, the information is stored as a list of two numbers. However, the arrangement of the numbers differs. Double-click e in the Workspace window and you see two separate entries, as shown in Figure 5-2. Notice that the Variables window shows e as a 2-x-1 list in which the entries flow vertically. FIGURE 5-2: Typing semicolon-separated numbers produces rows of values.

Separating values with a comma or a semicolon

It’s possible to create a matrix by combining commas and semicolons. The commas separate entries in the same row and the semicolons create new rows. To see this for yourself, type a=[1, 2; 3, 4] in the Command Window and press Enter. You see

a =

1 2

3 4 Notice how the output looks like the linear algebra you’re used to. MATLAB makes every effort to use a familiar interface when presenting information so that you don’t have to think about how to interpret the data. If the output doesn’t appear as you expect, it could be a sign that you didn’t create the information you expected, either.

Finding dimensions of matrices with the Size column

Figures 5-1 and 5-2 show one way to obtain the size of a numeric list (it appears in the upper-left corner of the window). However, you can use an easier method. Click the down arrow on the right side of the Workspace window and select Choose Columns ⇒ Size from the context menu. You may also find it helpful to display the minimum and maximum values for each entry. This information comes in handy when working with large vectors or matrices where the minimum and maximum values aren’t obvious. To obtain this information, Choose Columns ⇒ Min, and then choose Choose Columns ⇒ Max.

Depending on your computer screen, you may need to click and drag the Size, Min, and Max columns more to the left so that you can see them. You can also resize the window. Figure 5-3 shows the results of the entries you created in the previous sections. FIGURE 5-3: The Size column tells you the dimensions of your matrix or vector.

Creating a range of values using a colon

Typing each value in a list manually would be time-consuming and error-prone because you’d eventually get bored doing it. Fortunately, you can use the colon (:) to enter ranges of numbers in MATLAB. The number on the left side of the colon specifies the start of the range, and the number on the right side of the colon specifies the end of the range. To see this for yourself, type g=[5:10] and press Enter. You see

g =

5 6 7 8 9 10

Creating a range of values using linspace()

Using the colon to create ranges has a problem. MATLAB assumes that the step (the interval between numbers) is 1. However, you may want the numbers separated by some other value. For example, you might want to see 11 values between the range of 5 and 10, instead of just 6.

The linspace() function solves this problem. You supply the starting value, the ending value, and the number of values you want to see between the starting and ending value. To see how linspace() works, type g=linspace(5,10,11) and press Enter. You see

g =

Columns 1 through 5

5.0000 5.5000 6.0000 6.5000 7.0000

Columns 6 through 10

7.5000 8.0000 8.5000 9.0000 9.5000

Column 11

10.0000 In this case, the step value is 0.5. Each number is 0.5 higher than the last, and there are 11 values in the output. The range is from 5 to 10, just as in the colon example in the previous section. In short, using linspace() is a little more flexible than using the colon, but using the colon requires less typing and is easier to remember.

Adding a step to the colon method

It turns out that you can also specify the step when using the colon method. However, in this case, you add the step between the beginning and ending of the range when defining the range. So, you type the beginning number, the step, and the ending number, all separated by colons. To try this method for yourself, type g=[5:0.5:10] and press Enter. You see

g =

Columns 1 through 5

5.0000 5.5000 6.0000 6.5000 7.0000

Columns 6 through 10

7.5000 8.0000 8.5000 9.0000 9.5000

Column 11

10.0000 This is precisely the same output as that of the linspace() example. However, when using this method, you specify the step directly, so you don’t control the number of values you receive as output. When using the linspace() approach, you specify the number of values you receive as output, but MATLAB computes the step value for you. Each technique has advantages, so you need to use the one that makes sense for your particular need.

Transposing matrices with an apostrophe

Using the colon creates row vectors. However, sometimes you need a column vector instead. To create a column vector, you end the input with an apostrophe, which is also called a prime in MATLAB parlance. To see how this works for yourself, type h=[5:0.5:10]' and press Enter. You see

h =

5.0000

5.5000

6.0000

6.5000

7.0000

7.5000

8.0000

8.5000

9.0000

9.5000

10.0000

When you look at the Workspace window, you see that g is a 1-x-11 vector, while h is an 11-x-1 vector. The first entry is a row vector and the second is a column vector.

You can transpose matrices as well. The rows and columns change position. For example, earlier you typed a=[1,2;3,4], which produced

a =

1 2

3 4

To see how this matrix looks transposed, type i=[1,2;3,4]' and press Enter. You see

i =

1 3

2 4

NON-NUMERIC VECTORS AND MATRICES

Even though this chapter focuses almost exclusively on numeric vectors and matrices, MATLAB enables you to use other kinds of data to create vectors and matrices as well. In many cases, you see these other forms referred to as an array, rather than a vector, because the term vector has special meaning in math. For example, you can create a character array like this:

A = ['Hello, There!']

Notice that all the letters appear together in a single-quoted string, which is viewed by MATLAB as a 1-x-13 character array. However, when working with a character array, you can also create precisely the same array using A = ['Hello, ', 'There!']. However, if you place each of the character arrays in an individual array, separated by a semicolon, like this:

A = [['Hello,']; ['There!']]

you obtain a 2-x-6 character array, a matrix-like presentation, instead. Notice the use of a semicolon to separate dimensions. Again, MATLAB uses the term array, rather than matrix, because the term matrix has special meaning to mathematicians. Note that if you were to use A = ['Hello, '; 'There!'] instead, you’d receive an error message telling you that the array dimensions aren’t consistent, so the extra square brackets really are needed. A string array is somewhat different because you create it using a double-quoted series of character entries, like this:

B = ["One", "Two", "Three", "Four"]

The result is a 1-x-4 string array. Each string is separate. If you want a matrix-like presentation, you might use the following code:

B = [["One", "Two"]; ["Three", "Four"]]

which results in a 2-x-2 string array. Note that when working with string arrays, you can get by using B = ["One", "Two"; "Three", "Four"] instead (without the additional square brackets). Boolean arrays follow the same pattern as character and string arrays. You might create one like this:

C = [false, true, false, true]

The result is a 1-x-4 logical array. The point is that you need to maintain an open mind when working with vectors and matrices — it’s not all about the numbers. You see other examples of non-numeric forms as the book progresses.

Now that you know how to enter vectors and matrices in MATLAB, it’s time to see how to perform math using them. Adding and subtracting is a good place to start. The essential rule when adding and subtracting vectors and matrices is that they must be the same size. You can’t add or subtract vectors or matrices of different sizes because MATLAB will display an error message. Use the following steps to see how to perform this task:

1. Type a=[1,2;3,4] and press Enter.

You see

a =

1 2

3 4

2. Type b=[5,6;7,8] and press Enter.

You see

b =

5 6

7 8

3. Type c = a + b and press Enter.

This step adds matrix a to matrix b. You see

c =

6 8

10 12

4. Type d = b - a and press Enter.

This step subtracts matrix b from matrix a. You see

d =

4 4

4 4

5. Type e=[1,2,3;4,5,6] and press Enter.

You see

e =

1 2 3

4 5 6

If you attempt to add or subtract matrix e from either matrix a or matrix b, you see an error message. However, the following step tries to perform the task anyway.

6. Type f = e + a and press Enter.

As expected, you see the following error message:

Matrix dimensions must agree.

The error messages differ a little between addition and subtraction, but the idea is the same. The matrices must be the same size in order to add or subtract them.

It’s possible to perform addition and subtraction with non-numeric data. In fact, when performing certain character and string processing tasks, you do just that. For example, if you have the matrix a=[1,2;3,4] and the matrix b=["a", "b"; "c", "d"], then c = a+b would create the following output:

c =

2×2 string array

"1a" "2b"

"3c" "4d"

In this case, MATLAB converts the values in matrix a to strings, and then concatenates the values in matrix b to produce matrix c. However, the rules are different for character arrays, such as when you create d=['a', 'b'; 'c', 'd'] and then enter e=a+d to produce this output:

e =

98 100

102 104

This time, MATLAB converts the characters in matrix d to their numeric values (a=97, b=98, c=99, and d=100) and adds them to matrix a. You can also perform addition and subtraction with other non-numeric data types, such as logical arrays. In fact, you can also perform multiplication and division, as described in the next section, “Understanding the Many Ways to Multiply and Divide.”

Understanding the Many Ways to Multiply and Divide

After addition and subtraction come multiplication and division. MATLAB is just as adept in meeting these needs as it is in every other area. The following sections describe the many ways in which you can use multiplication and division in MATLAB.

Performing scalar multiplication and division

A scalar is just technobabble for ordinary numbers. When you multiply ordinary numbers by vectors and matrices, you get a result where every element is multiplied by the number. To try this for yourself, type a = [1,2;3,4] * 3 and press Enter. You see the following output:

a =

3 6

9 12

The example begins with the matrix, [1,2;3,4]. It then multiplies each element by 3 and places the result in a.

Division works in the same manner. To see how division works, type b = [6, 9; 12, 15] / 3 and press Enter. You see the following output:

b =

2 3

4 5

Again, the example begins with a matrix, [6, 9; 12, 15], and right divides it by 3. The result is stored in b. MATLAB supports both right division, in which the left side is divided by the right side (what most people would consider the standard way of doing things), and left division, in which the left side is divided by the right side. When working with scalars, whether you use right division or left division doesn’t matter as long as you divide the matrix by the scalar. To see this fact for yourself, type c = 3 \ [6, 9; 12, 15] and press Enter. (Notice the use of the backslash, \, for left division.) You get the same result as before:

c =

2 3

4 5

Employing matrix multiplication

Multiplication occurs at several different levels in MATLAB. The following sections break down the act of matrix multiplication so that you can see each level in progression.

Multiplying two vectors

Vectors are just matrices of only one row or column. Remember that you create a row vector by separating values using a comma, such as [1, 2]. To create column vectors, you use a semicolon, such as [3; 4]. You can also use prime to create a row or column vector. For example, [3, 4]' is equivalent to [3; 4]. (Pay particular attention to the use of commas and semicolons.) When you want to multiply one vector by another, you must have one row and one column vector. Try it for yourself by typing d = [1, 2] * [3; 4] and pressing Enter. You get the value 11 for output. Of course, the method used to perform the multiplication is to multiply the first element in the row vector by the first element of the column vector, and add the result to the multiplication of the second element of the row vector and the second element of the column vector. What you end up with is d = 1 * 3 + 2 * 4. This form of multiplication is also called an inner product or a dot product.

You can also use the dot() function to obtain a dot product by typing d = dot([1, 2], [3; 4]) and pressing Enter. The dot() function is smarter than using the * operator because it will automatically transpose a vector when necessary. For example, typing d = [1, 2, 3] * [4, 5, 6] and pressing Enter produces an error, but typing d = dot([1, 2, 3], [4, 5, 6]) and pressing Enter produces an output of 32. To obtain the same value using the * operator, you need to type d = [1, 2, 3] * [4; 5; 6] and press Enter (note the semicolons), which transposes the second vector.

You can also create an outer product using MATLAB. In this case, each element in the first vector is multiplied by every element of the second vector (technically matrix multiplication), and the results of each multiplication are placed in a separate element. To put this in perspective, you’d end up with a 2-x-2 matrix consisting of [3 * 1, 3 * 2; 4 * 1, 4 * 2]. The easiest way to see how this works is by trying it yourself. Type e = [3; 4] * [1, 2] and press Enter. You see

e =

3 6

4 8 Another way to perform this task is to use the bsxfun() function: e = bsxfun(@times, [1, 2], [3; 4]. You supply a function name (see https://www.mathworks.com/help/matlab/ref/bsxfun.html or type help('bsxfun') and press Enter) to perform an element-by-element math operation on two objects (vectors, in this case). This example uses the @times function, which performs multiplication. The two inputs are a row vector and a column vector. The output is a 2-x-2 matrix using the same technique as the multiplication approach.

Multiplying a matrix by a vector

When performing multiplication of a matrix by a vector, the order in which the vector appears is important. Row vectors appear before the matrix, but column vectors appear after the matrix. To see how the row vector approach works, type f = [1, 2] * [3, 4; 5, 6] and press Enter. You see an output of

f =

13 16

The first element is produced by 1 * 3 + 2 * 5. The second element is produced by 1 * 4 + 2 * 6. However, the number of rows in the matrix must agree with the number of elements in the vector. For example, if the vector has three elements in a row, the matrix must have three elements in a column to match. To see how this works, type g = [1, 2, 3] * [4, 5; 6, 7; 8, 9] and press Enter. The result is

g =

40 46

The number of matrix columns controls the number of output elements. For example, if the matrix were to have three columns, the output would have three elements. To see this principle in action, type h = [1, 2, 3] * [4, 5, 6; 7, 8, 9; 10, 11, 12] and press Enter. The result is

h =

48 54 60

Working with a column vector is similar to working with a row vector, except that the position of the vector and matrix are exchanged. For example, if you type i = [4, 5, 6; 7, 8, 9; 10, 11, 12] * [1; 2; 3] and press Enter, you see this result:

i =

32

50

68

Notice that the output is a column vector instead of a row vector. The result is produced by these three equations:

1 * 4 + 2 * 5 + 3 * 6

1 * 7 + 2 * 8 + 3 * 9

1 * 10 + 2 * 11 + 3 * 12

The order of the multiplication differs because you’re using a column vector instead of a row vector. MATLAB produces the same result as you would get when performing the task using other means, but you need to understand how the data-entry process affects the output.

Multiplying two matrices

When working with matrices, the number of columns in the first matrix must agree with the number of rows in the second matrix. For example, if the first matrix contains two rows containing three entries each, the second matrix must contain three rows and two entries each. To see this for yourself, type j = [1, 2, 3; 4, 5, 6] * [7, 8; 9, 10; 11, 12] and press Enter. You see the output as

j =

58 64

139 154

Notice that the number of rows in the first matrix determines the number of rows in the result. Likewise, the number of columns in the second matrix determines the number of columns in the result. The output of the first column, first row is defined by 1 * 7 + 2 * 9, + 3 * 11. Likewise, the output of the second column, first row is defined by 1 * 8 + 2 * 10 + 3 * 12. The matrix math works just as you would expect. Order is important when multiplying two matrices (just as it is when working with vectors). You can create the same two matrices, but obtain different results depending on order. If you reverse the order of the two matrices in the previous example by typing k = [7, 8; 9, 10; 11, 12] * [1, 2, 3; 4, 5, 6] and pressing Enter, you obtain an entirely different result:

k =

39 54 69

49 68 87

59 82 105

Again, it pays to know how the output is produced. In this case, the output of the first column, first row is defined by 7 * 1 + 8 * 4. Likewise, the output of the second column of the first row is defined by 7 * 2 + 8 * 5.

Dividing two vectors

MATLAB produces an output if you try to divide two vectors, even though the result isn’t useful. You can read the details at https://van.physics.illinois.edu/qa/listing.php?id=24304 and many other places online. For example, if you type l = [2, 3, 4] / [5, 6, 7] and press Enter, you receive a result of

l =

0.5091

Likewise, you could try typing l = [2, 3, 4] \ [5, 6, 7] and press Enter. The results would be different:

l =

0 0 0

0 0 0

1.2500 1.5000 1.7500

You get the same reproducible results every time, but you can see that they’re interesting, at best.

Effecting matrix division

As with matrix multiplication, matrix division takes place at several different levels. The following sections explore division at each level.

Dividing a vector by a scalar

Dividing a vector by a scalar and producing a usable result is possible. For example, type m = [2, 4, 6] / 2 and press Enter. You see the following result:

m =

1 2 3

Each of the entries is divided by the scalar value. Notice that this is right division. Using left division (m = [2, 4, 6] \ 2) would produce an unusable result; however, using m = 2 \ [2, 4, 6] would produce the same result as before. MATLAB would do its best to accommodate you with a result, just not one you could really use. (See the “Dividing two vectors” section for an explanation.)

Dividing a matrix by a vector

When dividing a matrix by a vector, defining the sort of result you want to see is important. For example, if you use n = [2, 4] / [2, 4; 6, 8], you receive the following output, which is actually solving a system of linear equations (xb = a):

n =

1 0

You can obtain the same result using the mrdivide() function (see https://www.mathworks.com/help/matlab/ref/mrdivide.html), and it’s the equivalent of n = [2, 4] * inv([2, 4; 6, 8]).

However, most people want to perform an element-by-element division. In this case, you use array division: n = [2, 4; 6, 8] ./ [2, 4] (notice the dot before the division symbol). You see the following output:

n =

1 1

3 2

In this case, the element in column 1, row 1 is defined by 2 / 2. Likewise, the element in column 1, row 2 is defined by 6 / 2. You can also use the bsxfun() function with the @rdivide function to obtain the same result.

Dividing two matrices

When dividing two matrices, the dimensions of the two matrices must agree. For example, you can’t divide a 3-x-2 matrix by a 2-x-3 matrix — both matrices must be the same dimensions, such as 3-x-2. To see how this works, type o = [2, 4; 6, 8] / [1, 2; 3, 4] and press Enter. You see the following result:

o =

2 0

0 2

Performing left division of two matrices is also possible. To see the result of performing left division using the same matrices, type p = [2, 4; 6, 8] \ [1, 2; 3, 4] and press Enter. Here’s the result you see:

p =

0.5000 0

0 0.5000 As with vector division in the previous section, matrix division isn’t array division. What you really do is multiply one matrix by the inverse of the other. For example, using the two matrices in this section, you can accomplish the same result of left division by typing q = [2, 4; 6, 8] * inv([1, 2; 3, 4]) and pressing Enter. To perform right division, you simply change the inverted matrix by typing r = inv([2, 4; 6, 8]) * [1, 2; 3, 4] and pressing Enter. The inv() function always returns the inverse of the matrix that you provide as input (assuming an inverse exists), so you can use it to help you understand precisely how MATLAB is performing the task. However, using the inv() function is computationally inefficient. To make your scripts run faster, dividing is always better.

You can use the inv() function in many ways. For example, multiplying any matrix by its inverse, such as by typing s = [1, 2; 3, 4] * inv([1, 2; 3, 4]), yields the identity matrix:

s =

1.0000 0

0.0000 1.0000

Element-by-element (array) division follows the same pattern with matrixes as it does with vectors. So, when you type t = [2, 4; 6, 8] .\ [1, 2; 3, 4] and press Enter, you obtain the following result:

t =

0.5000 0.5000

0.5000 0.5000

Likewise, you can perform right division using u = [2, 4; 6, 8] ./ [1, 2; 3, 4] to obtain the following result:

u =

2 2

2 2

Creating powers of matrices

Sometimes you need to obtain the power or root of a matrix. MATLAB provides several different methods for accomplishing this task. The most common method is to use the circumflex (^) to separate the matrix from the power to which you want to raise it. To see how this works, type v = [1, 2; 3, 4]^2 and press Enter. The output is the original matrix squared, as shown here:

v =

7 10

15 22

To obtain the root of a matrix, you use a fractional value as input. For example, to obtain the square root of the previous example, you use a value of 0.5. To see this feature in action, type x = [1, 2; 3, 4]^0.5 and press Enter. You see the following output:

x =

0.5537 + 0.4644i 0.8070 - 0.2124i

1.2104 - 0.3186i 1.7641 + 0.1458i

To verify your values, type int32(x^2) and press Enter. You should see the original array values. The reason you use int32() is to convert the complex numbers to integer values, just like the original matrix.

It’s even possible to obtain the inverse of a matrix by using a negative power. For example, try typing z = [1, 2; 3, 4]^(–1) and pressing Enter (notice that the –1 is enclosed in parentheses to avoid confusion). You see the following output:

z =

-2.0000 1.0000

1.5000 -0.5000

CHECKING MATRIX RELATIONS

This chapter discusses a number of techniques to perform any given task. For example, you can create the inverse of a matrix using the inv() function, or you can simply raise it to a power of –1. The problem is that you don’t really know that they are equal outputs. Fortunately, you can use relational operators with matrixes, as in: inv([1, 2; 3, 4]) == [1, 2; 3, 4]^(-1). The output you see is a logical array:

ans =

2×2 logical array

1 1

1 1

A value of 1 indicates true. Consequently, if you were to ask the opposite question, inv([1, 2; 3, 4]) ~= [1, 2; 3, 4]^(-1), the output would be a logical array of 0s, indicating false for each comparison. It shouldn’t surprise you, then, that when you compare [1, 3; 6, 8] >= [2, 4; 6, 8], to determine which elements in the first matrix are greater than or equal to the elements in the second matrix, you see a logical array output of

ans =

2×2 logical array

0 0

1 1 MATLAB also provides the means for performing array powers and roots. For example, aa = [1, 2; 3, 4].^2 produces the following output, in which each element is multiplied by itself (note the addition of the period before the circumflex):

aa =

1 4

9 16

Using complex numbers

Complex numbers consist of a real part and an imaginary part (see https://www.mathsisfun.com/numbers/imaginary-numbers.html for a quick overview of imaginary numbers). MATLAB uses the i and j constants to specify the imaginary part of the number. For example, when you compute the square root of the matrix [1, 2; 3, 4], you obtain an output that contains imaginary numbers. To see this for yourself, type ad = [1, 2; 3, 4]^0.5 and press Enter. You see the following result:

0.5537 + 0.4644i 0.8070 - 0.2124i

1.2104 - 0.3186i 1.7641 + 0.1458i The first column of the first row contains a real value of 0.5537 and an imaginary value of 0.4644i. The i that appears after the value 0.4644 tells you that this is an imaginary number. The j constant means the same thing as the i constant, except that the j constant is used in electronics work (i is already used to represent current).

You can perform tasks with imaginary numbers just as you would any other number. For example, you can square the ad matrix by typing ae = ad^2 and pressing Enter. The result might not be what you actually wanted, though:

ae =

1.0000 + 0.0000i 2.0000 + 0.0000i

3.0000 - 0.0000i 4.0000 + 0.0000i

After a matrix includes imaginary numbers, you need to convert them to obtain a desired format. For example, if you type af = int32(ad^2) and press Enter, you obtain the desired result, shown here:

af =

2×2 int32 matrix

1 2

3 4

The int32() function performs the required conversion process for you. Of course, using int32(), or any other function of the same type, at the wrong time can result in data loss. For example, if you type ag = int32([1, 2; 3, 4]^0.5) and press Enter, you lose not only the imaginary part of the number but the fractional part as well. The output looks like this:

ag =

2×2 int32 matrix

1 1

1 2

MATLAB assumes that you know what you’re doing, so it doesn’t stop you from making critical errors. The output conversion functions are

· double()

· single()

· int8()

· int16()

· int32()

· int64()

· uint8()

· uint16()

· uint32()

· uint64()

· complex()

Working with exponents

You use the matrix exponential to perform tasks such as solving differential equations (read about them at http://www.sosmath.com/matrix/expo/expo.html). MATLAB provides two functions for working with exponents directly (the article at https://www.mathworks.com/help/matlab/math/matrix-exponentials.html offers interesting reading if you want to see other ways to perform the task). The first is the expm() function, which calculates a standard matrix exponential. For example, when you type ah = expm([1, 2; 3, 4]) and press Enter, you see this result:

ah =

51.9690 74.7366

112.1048 164.0738

MATLAB also makes it easy to calculate an element-by-element exponential using the exp() function. To see how this works, type ai = exp([1, 2; 3, 4]) and press Enter. You see the following output:

ai =

2.7183 7.3891

20.0855 54.5982

Working with Higher Dimensions

A vector is one dimensional — just one row or one column. A matrix is a two-dimensional table, much like the kind you’re used to with Excel spreadsheets, with rows being one dimension and columns being the other. You can go as high as you want. If a matrix is like a page in a book (two dimensions), three dimensions is like the book itself, and four like a shelf of books. In fact, there is no limit to the number of dimensions you can use to express an idea or data element. Images are an example of computational objects that rely on more than one dimension:

· The first dimension is the x coordinate of a pixel.

· The second dimension is the y coordinate of a pixel.

· The third dimension is the pixel color.

Now that you have a better idea of how you might use more than just two dimensions, it’s time to see how you can implement them. The following sections describe how to work with multiple dimensions when using MATLAB.

Creating a multidimensional matrix

MATLAB provides a number of ways to create multidimensional arrays. The first method is to simply tell MATLAB to create it for you and fill each of the elements with zeros. The zeros() function helps you perform this task. To create a 2-x-3-x-3 matrix, you type aj = zeros(2, 3, 3) and press Enter. You see the following output:

aj(:,:,1) =

0 0 0

0 0 0

aj(:,:,2) =

0 0 0

0 0 0

aj(:,:,3) =

0 0 0

0 0 0

This output tells you that there are three stacked 2-x-3 matrices, and each one is filled with zeros. Of course, you might not want to start out with a matrix that’s filled with zeros, so you can use another approach. The following steps help you create a 2-x-3-x-3 matrix that is already filled with data:

1. Type ak(:,:,1) = [1, 2, 3; 4, 5, 6] and press Enter.

You see the following result:

ak =

1 2 3

4 5 6

This step creates the first page of the three-dimensional matrix. You want three pages, so you actually need to perform this step three times.

2. Type ak(:,:,2) = [7, 8, 9; 10, 11, 12] and press Enter.

MATLAB adds another page, as shown:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

10 11 12

If you look at the Workspace window at this point, you see that the size column for ak is now 2 x 3 x 2. It’s at this point that you see the third dimension added. Before you added this second page, MATLAB simply treated ak as a 2-x-3 matrix, but now it has the third dimension set.

3. Type ak(:,:,3) = [13, 14, 15; 16, 17, 18] and press Enter.

The output now looks much like the aj output, except that the elements have values, as shown here:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

10 11 12

ak(:,:,3) =

13 14 15

16 17 18

You don’t have to define assigned values using multiple steps. The cat() function lets you create the entire three-dimensional matrix in one step. The first entry that you make for the cat() function is the number of dimensions. You then add the data for each dimension, separated by commas. To see how this works, type al = cat(3, [1, 2, 3; 4, 5, 6], [7, 8, 9; 10, 11, 12], [13, 14, 15; 16, 17, 18]) and press Enter. You see this output (which looks amazingly like the ak matrix):

al(:,:,1) =

1 2 3

4 5 6

al(:,:,2) =

7 8 9

10 11 12

al(:,:,3) =

13 14 15

16 17 18 You may also decide that you don’t want to type that much but still don’t want zeros in the matrix. In this case, use the randn() function for random normally distributed data, or use the rand() function for uniformly distributed data. This function works just like the zeros() function, but it fills the elements with random data.

CREATING NON-NUMERIC MULTIDIMENSIONAL ARRAYS

You can create multidimensional arrays of data types other than numbers. For example, if you want a 2-x-3-x-3 array of strings, you can create it using strings(2, 3, 3). You can then assign values to the array elements much as you do with numbers.

In some cases, when working with non-numeric arrays, it’s actually easier to start with a 2D array and then extend it. For example, you might start with a logical array like this: c = [true, false; true, false]. You could then extend it to a third dimension like this: c(:, :, 2) = [false, true; false, true], with an output like this:

2×2×2 logical array

c(:,:,1) =

1 0

1 0

c(:,:,2) =

0 1

0 1

To see how this function works, type am = randn(2, 3, 3) and press Enter. You see a three-dimensional array filled with random data. Your output isn’t likely to look precisely like the following output, but this output does give you an idea of what to expect:

am(:,:,1) =

1.4090 0.6715 0.7172

1.4172 -1.2075 1.6302

am(:,:,2) =

0.4889 0.7269 0.2939

1.0347 -0.3034 -0.7873

am(:,:,3) =

0.8884 -1.0689 -2.9443

-1.1471 -0.8095 1.4384

Accessing a multidimensional matrix

No matter how you create the matrix, eventually you need to access it. To access the entire matrix, you simply use the matrix name, as usual. However, you might not need to access the entire matrix. For example, you might need to access just one page. The examples in this section assume that you created matrix ak in the previous section. To see just the second page of matrix ak, you type ak(:, :, 2) and press Enter. Not surprisingly, you see the second page, as shown here:

ans =

7 8 9

10 11 12

The colon (:) provides a means for you to tell MATLAB that you want the entire range of a matrix dimension. The values are rows, columns, and pages in this case. So the request you made was for the entire range of page 2. You could ask for just a row or column. To get the second row of page 2, you type ak(2, :, 2) and press Enter. The output looks like this:

ans =

10 11 12

The second column of page 2 is just as easy. In this case, you type ak(:, 2, 2) and press Enter. The output appears in column format, like this:

ans =

8

11

Accessing an individual value means providing all three values. When you type ak(2, 2, 2) and press Enter, you get 11 as the output because that’s the value in row 2, column 2, of page 2 for matrix ak.

You also have access to range selections for multidimensional matrices. In this case, you must provide a range for one of the entries. For example, if you want to obtain access to row 2, columns 1 and 2, of page 2 for matrix ak, you type ak(2, [1:2], 2) and press Enter. Notice that the range appears within square brackets, and the start and end of the range are separated by a colon. Here is the output you see in this case:

ans =

10 11 The use of ranges works wherever you need them. For example, say that you want rows 1 and 2, columns 1 and 2, of page 2. You type ak([1:2], [1:2], 2) and press Enter. The result looks like this:

ans =

7 8

10 11

Replacing individual elements

As you work through problems and solve difficulties, you might find changing some of the data in a matrix necessary. The problem is that you don’t want to have to re-create the matrix from scratch just to replace one value. Fortunately, you can replace individual values in MATLAB. The examples in this section assume that you created matrix ak in the “Creating a multidimensional matrix” section, earlier in this chapter.

The previous section tells you how to access matrix elements. You use this ability to change values. For example, the value in row 2, column 2, of page 2 in matrix ak is currently set to 11. You may decide that you really don’t like the number 11 there and want to change it to 44 instead. To perform this task, type ak(2, 2, 2) = 44 and press Enter. You see the following result:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

10 44 12

ak(:,:,3) =

13 14 15

16 17 18 Notice that MATLAB displays the entire matrix. Of course, you may not want to see the entire matrix every time you replace a single value. In this case, end the command with a semicolon. When you type ak(2, 2, 2) = 44; and press Enter, the change still takes place, but you don’t see the result onscreen. For now, continuing to display the information is a good idea so that you can tell whether you have entered the commands correctly and have obtained the desired result.

Replacing a range of elements

If you have a number of values to replace in a matrix, replacing them one at a time would become boring. More important, you start to make mistakes after a while, and your results don’t come out as you thought they would. Replacing a range of values with a single command is the best idea in this case. The examples in this section assume that you created matrix ak in the “Creating a multidimensional matrix” section, earlier in this chapter.

You have many different ways to make replacements to a range of elements in your existing matrix. Of course, before you can replace a range of elements, you need to know how to access them. The “Accessing a multidimensional matrix” section, earlier in this chapter, tells you how to access matrix elements.

You can make a single value replacement for a range. Say that you want to replace row 2, columns 1 and 2, of page 2 with the number 5. To perform this task, type ak(2, [1:2], 2) = 5 and press Enter. The single value appears in both places, as shown in this output:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

5 5 12

ak(:,:,3) =

13 14 15

16 17 18

Of course, a single value replacement might not work. You can also create range replacements in which you replace each element with a different value. For example, you might want to replace row 2, column 1, of page 2 with the number 22, and row 2, column 2, of page 2 with the number 33. To perform this task, you type ak(2, [1:2], 2) = [22, 33] and press Enter. Here is the output you see:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

22 33 12

ak(:,:,3) =

13 14 15

16 17 18

Column changes work the same way. In this case, you might want to replace row 1, column 3, of page 2 with the number 44, and row 2, column 3, of page 2 with the number 55. To perform this task, you type ak([1:2], 3, 2) = [44, 55] and press Enter. Notice that you didn’t have to define the input vector using a column format. Here’s the result you see:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 44

22 33 55

ak(:,:,3) =

13 14 15

16 17 18

When replacing a rectangular range, you need to use a proper matrix for input. For example, you might want to replace a rectangular range between columns 1 and 3, rows 1 and 2, of page 2 with the values 7 through 12. To perform this task, you type ak(1:2, 1:3, 2) = [7:9;10:12] and press Enter. Notice that the input uses ranges in this case, too. Here’s the result you see:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

10 11 12

ak(:,:,3) =

13 14 15

16 17 18

Modifying the matrix size

You might not think that resizing a matrix is possible, but MATLAB can do that, too. It can make the matrix larger or smaller. The technique for making the matrix smaller is a bit of a trick, but it works well, and you likely will have a need for it at some point. The examples in this section assume that you created matrix ak in the “Creating a multidimensional matrix” section, earlier in this chapter.

As with range replacement, you need to know how to access ranges before you start this section. The “Accessing a multidimensional matrix” section, also earlier in this chapter, tells you how to access matrix elements.

The current ak matrix is 2 x 3 x 3. You might want to add another row, even if that row consists only of zeros, to make the matrix square for some advanced task you need to perform. Some tasks work properly only with square matrices, so this is a real concern. To add another row to the existing matrix, type ak(3, :, :) = 0 and press Enter. You see the following result:

ak(:,:,1) =

1 2 3

4 5 6

0 0 0

ak(:,:,2) =

7 8 9

10 11 12

0 0 0

ak(:,:,3) =

13 14 15

16 17 18

0 0 0 All three pages now have another row. However, you might decide that you really don’t want that extra row after all. To delete the row, you need to perform a bit of a trick — you set the row to a null (empty) value using an empty matrix ([]). To see how this works, type ak(3, :, :) = [] and press Enter. You see the following result:

ak(:,:,1) =

1 2 3

4 5 6

ak(:,:,2) =

7 8 9

10 11 12

ak(:,:,3) =

13 14 15

16 17 18

At this point, you probably wonder what would happen if you added a column or row to just a single page. Try typing ak(:, 4, 1) = [88, 99] and pressing Enter. This command adds a fourth column to just page 1 and fills it with the values 88 and 99. MATLAB provides the following output:

ak(:,:,1) =

1 2 3 88

4 5 6 99

ak(:,:,2) =

7 8 9 0

10 11 12 0

ak(:,:,3) =

13 14 15 0

16 17 18 0

Notice that the other pages also have a fourth column now. The column is filled with zeros, but MATLAB automatically adds it for you to keep things tidy. Note that if you try to get rid of a column in the same way by typing ak(:, 4, 1) = [] and pressing Enter, you see a A null assignment can have only one non-colon index. error message. You must type ak(:, 4, :) = [] and press Enter instead.

Using cell arrays and structures

The matrices you have created so far all contain the same data type, such as double or uint8. Every matrix you create will contain data of the same type — you can’t mix types in a matrix. When performing certain tasks, such as machine learning, you need other structures:

· A cell array works much like a spreadsheet.

· A structure works much like a database record.

These two containers let you store other kinds of data, and mix and match types as needed. You can use them to create a small database or some sort of alternative storage on your machine without resorting to another application. The following sections provide an introduction and point you to more help in case you need to know more.

Understanding cell arrays

Cell arrays are naturals for spreadsheets because an individual cell in a cell array is like a cell in a spreadsheet. In fact, when you import a spreadsheet into MATLAB, each cell in the spreadsheet becomes a cell in a MATLAB cell array. Because spreadsheets are so popular, you’re more likely to encounter a cell array than a structure.

You use the cell() function to create a new cell array. For example, to create a 2-x-2-x-2 cell array, you type an = cell(2, 2, 2) and press Enter. You see this result:

2×2×2 cell array

an(:,:,1) =

{0×0 double} {0×0 double}

{0×0 double} {0×0 double}

an(:,:,2) =

{0×0 double} {0×0 double}

{0×0 double} {0×0 double}

The cells are empty at this point. Cell arrays rely on a different kind of brackets, the curly braces ({}), to provide access to individual elements. In order to make the an cell array useful, begin by typing the following lines of code, pressing Enter after each line:

rng(5)

an{1,1,1}='George';

an{1,2,1}='Smith';

an{2,1,1}=rand();

an{2,2,1}=uint16(1953);

an{1,1,2}=true;

an{1,2,2}=false;

an{2,1,2}=14.551+2.113i;

an{2,2,2}='The End!'

Because all the lines except for the last one ended with a semicolon, you didn’t see any output. However, after you type the last line, you see the following output from MATLAB:

2×2×2 cell array

an(:,:,1) =

{'George'} {'Smith'}

{[0.2220]} {[ 1953]}

an(:,:,2) =

{[ 1]} {[ 0]}

{[14.5510 + 2.1130i]} {'The End!'} Note that this example sets the seed value for the random number generator using rng(5) so that the first value produced by rand() is the same unless you specify a different generator (see the rng() documentation at https://www.mathworks.com/help/matlab/ref/rng.html for details). The advantage of this approach is that you obtain the same numbers in the same sequence when you perform testing. However, you want to use a unique seed when working with production applications so that the rand() output truly does appear random.

The output looks a little different from a multidimensional matrix. You can access it the same way, except that you use curly braces. For example, type an{1, :, 2} and press Enter to see the first row of page 2. The result looks like this:

ans =

logical

1

ans =

logical

0 Each of the entries is treated as a separate item, but you can select ranges and work with individual values, just as you do when working with a multidimensional matrix. However, you must use the curly braces when working with cell arrays. You can distinguish between cell arrays and matrices in the Workspace window by the icons they use. The cell array icon contains a pair of curly braces, so it contrasts well with the matrix icon, which looks like a mini table. The Value column also specifically tells you that the entry is a cell rather than a specific data type, such as a double. You can find additional information about cell arrays at https://www.mathworks.com/help/matlab/cell-arrays.html.

Understanding structures

Structures are more closely related to SQL database tables than spreadsheets. Each entry consists of a field name and value pair. The field names are generally descriptive strings, but the values can be anything that relates to that field name. To get a better idea of how a structure works, type MyStruct = struct('FirstName', 'Amy', 'LastName', 'Jones', 'Age', 32, 'Married', false) and press Enter. You see the following output:

MyStruct =

struct with fields:

FirstName: 'Amy'

LastName: 'Jones'

Age: 32

Married: 0

Notice how the field names are paired with their respective values. A structure is designed to reside in memory like a database. Currently, MyStruct has just one record in it. You can access this record by typing MyStruct(1) and pressing Enter. The results are as follows:

ans =

struct with fields:

FirstName: 'Amy'

LastName: 'Jones'

Age: 32

Married: 0

Dealing with an entire record probably isn’t what you had in mind, though. To access a particular field, you type a period, followed by the field name. For example, type MyStruct.LastName and press Enter to access the LastName field. You get the following answer:

ans =

'Jones'

Because MyStruct contains just one record, you don’t have to include the record number to access the LastName field. A single record structure isn’t very useful. You might have quite a few records in a real structure. To add another record to MyStruct, type MyStruct(2) = struct('FirstName', 'Harry', 'LastName', 'Smith', 'Age', 35, 'Married', true) and press Enter. The output might surprise you this time. You see

MyStruct =

1x2 struct array with fields:

FirstName

LastName

Age

Married

The output tells you how many records are in place. You can test for the second record by typing MyStruct(2) and pressing Enter. The output is precisely as you expect:

ans =

struct with fields:

FirstName: 'Harry'

LastName: 'Smith'

Age: 35

Married: 1 Don’t limit your input of structures to the common data types. Structure data may contain a matrix, even multidimensional matrices, and you can mix sizes. In addition, structures and cell arrays can contain each other. An element in a structure can be a cell array, and a cell in a cell array can be a structure. The point is that these are extremely flexible ways to store information when you need them; however, you shouldn’t make things overly complex by using them when you don’t need them. If you can create storage that uses one common data type, matrices are the way to go. You can find additional information about structures at https://www.mathworks.com/help/matlab/structures.html.

Using the Matrix Helps

As you work with matrices, you may need to test your code, and MATLAB has provided some help in the form of ways to create a matrix (Table 5-1), test matrices (Table 5-2), and diagnose matrix problems (Table 5-3). The tables in this section help you work more productively with matrices and get them working considerably faster. You can find additional matrix help at https://www.mathworks.com/help/matlab/matrices-and-arrays.html. When working with functions such as rand() and randn(), MATLAB provides a pseudo-random value based on a constantly changing seed value, which may not prove effective for testing. To obtain the same series of values every time you start your application, you can use the rng() function to set the seed value at the outset. In this way, the output of rand() or randn() will be the same every time you start the testing over. You can discover more about rng() at https://www.mathworks.com/help/matlab/ref/rng.html.

TABLE 5-1 Matrix Creation

 Function What It Does Generic Call Example zeros() Creates a matrix of all zeros zeros(), where is a positive integer number, two number arguments, or a vector of numbers. >> zeros(3) ans = 0 0 0 0 0 0 0 0 0 ones() Creates a matrix of ones ones(), where is a positive integer number, two number arguments, or a vector of numbers. >> ones(3) ans = 1 1 1 1 1 1 1 1 1 eye() Creates an identity matrix with one on the main diagonal and zero elsewhere eye(), where is a positive integer number, two number arguments, or a vector of numbers. This call doesn’t allow you to create N-dimensional arrays, which have more than two dimensions. The rand() and randn() functions do allow for N-dimensional arrays. >>eye(3) ans= 1 0 0 0 1 0 0 0 1 rand() Creates a matrix of uniformly distributed random numbers rand(), where works similarly to the argument(s) of eye(). You could also use rand(3, 3, 3) to produce a 3-x-3-x-3 array. >>rand(3) ans= 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575 randn() Creates a matrix of normally distributed random numbers (mean=0, SD=1) randn(), where works similarly to the argument(s) of eye(). You could also use randn(3, 3, 3) to produce a 3-x-3-x-3 array. >> randn(3) ans = 0.5377 0.8622 -0.4336 1.8339 0.3188 0.3426 -2.2588 -1.3077 3.5784 blkdiag() Makes a block diagonal matrix blkdiag(a,b,c,…), where a, b, c, … are matrices. >> blkdiag(ones(2),ones(2)) ans = 1 1 0 0 1 1 0 0 0 0 1 1 0 0 1 1

TABLE 5-2 Test Matrices

 Function What It Does Generic Call Example magic() Creates a magic square matrix — the sum of rows, columns, and diagonals are the same. magic(n), where n is the number of rows and columns. >> magic(3) ans = 8 1 6 3 5 7 4 9 2 gallery() Produces a wide variety of test matrices for diagnosis of your code gallery(…',…, j),where 'option' is a string that defines what task to perform, such as binomial, which creates a binomial matrix. is a positive integer number, two number arguments, or a vector of numbers. Each different positive integer j produces a different matrix. >> gallery('normaldata',3,3) ans = 0.9280 -0.7230 0.2673 0.1733 -0.5744 1.3345 -0.6916 -0.3077 -1.3311