Arrays, Creating Vectors/Matrices and their Operations, Dot and Cross Product

In today’s lesson, we will discuss the following topics:

1. What is an Array?

2. How to Create a Matrix (plural – Matrices)

3. How to Create a Vector

4. Sub-Matrices

5. Vector and Matrix Operations

6. Dot and Cross Products

VIDEO COMING SOON

What is an Array?

An array in MATLAB can be used to described a vector or matrix, which are both specific types of arrays. There are other higher dimensional objects that an array can be used to refer to as well, but we will stick with vectors and matrices for now.

How to Create a Matrix (plural – Matrices)

A matrix is a 2D, rectangular set of data (an array) with multiple columns (columns are usually denonated with n) and rows (rows are usually denoted with m). A matrix is commonly denoted with both # of rows and # of columns, m x n. The elements in the matrix can be numbers, true/false values, dates and times, strings, or some other MATLAB data type.

To create a matrix in MATLAB, we use square brackets and enter numerical values (also called elements of the matrix). The numbers can, but don’t have to, have commas in between them. By default, this creates a horizontal row of numbers.

Then we enter semicolons to indicate we are making a new row, and together this creates a matrix when there are multiple rows together, separated by semicolons (eg. the rows I have in the example below read side to side – 1 2 3 4 then 3 4 5 6 then 3 2 3 5 then 5 3 2 1. The columns read up and down instead of side to side).

Note that all the rows have to be the same size (each row needs the same amount of numbers in it) so they can be “stacked” on top of each other to create a matrix. Here is an example where I have 4 numbers in each row – you’ll notice how using commas between the numbers doesn’t make a difference in the output:

This would be a 4 x 4 matrixm x n meaning rows x columns. We have 4 rows and 4 columns, so it’s 4 x 4. This can also be read as “4 by 4 matrix.”

Also note that when we use semicolons here in between numbers, it is NOT the same as a semicolon we use to suppress outputs! These semicolons are used to make a new row in a matrix.

To show what happens when all the rows don’t have the same number of elements, here’s an example. I tried making a matrix where one of the rows has 3 numbers instead of 4, and this error came up:

How to Create a Vector

A vector is a special form of a matrix – it is a matrix with only one row or one column. Sometimes when referring to vectors, you’ll notice that it might also be referred to as a matrix, since it’s just a simpler form of one. To create a vector in MATLAB, we use square brackets [ ] and we type the numbers in there. They can, but don’t HAVE to be, separated by a comma (you can see the answers are the same with and without commas in the example below).

The example vector A below contains the values 1 2 3 4. By default, vectors are made into rows (rows are horizontal). This is called a row vector. If we want to make it into a column, we can either enter it as a column vector, or we have to do something called transpose of a vector. I discuss transpose later on in this post, but here is an example of a row vector:

Like I mentioned above, if you don’t want the output to be a default row vector that you need to convert to a column vector through using the transpose command, you can make a column vector directly by entering the numbers with semicolons in between:

Sub-Matrices

A sub-matrix is a matrix taken from within a matrix. To create a sub-matrix, you will need to have a matrix already made in your code. Then you can take a smaller chunk of this matrix and it will become a sub-matrix.

To select a smaller matrix within an existing one, use the following syntax: variable([rows],[columns]). ‘variable’ will be replaced with the variable name of the array, and ‘rows’ / ‘columns’ will be replaced with the numbers of the rows and columns you’d like to keep in the sub-matrix.

In this example here, I have selected the first 2 rows of matrix A. This is indicated by the [1 2]. I then selected all 3 columns of the matrix. This is indicated by [1 2 3]. The output sub-matrix selected the first 2 rows and all 3 columns of the original matrix to give me the new 2×3 sub-matrix (2 rows by 3 columns).

The rows and columns you select don’t have to be right next to each other either. In this example, I used the same matrix but selected the 1st and 3rd rows, rather than the first 2 rows. This output a sub-matrix that included all 3 columns and only the 1st and 3rd rows of the original matrix A:

Vector and Matrix Operations

When we create a vector or a matrix (I’m going to call these arrays moving forward, it’s easier to type), there are many different operations that can be performed on it. We could do mathematical operations, such as addition, subtraction, multiplication, or division. We could also add, subtract, multiply, or divide columns and rows with one another. We could add (aka append) a row or column to the end of the vector or matrix, or delete one. We could get MATLAB to tell us the minimum, or the maximum, number in the set. And much more! Let’s take a look at these, with examples below each operation:

(a) Transpose

The transpose of an array means it will flip the rows and columns – all the columns become rows, and vice versa. Use a single apostrophe next to the matrix or vector variable in order to transpose it. Here I have created a vector A, and typed A’ as my next command. See how it turned the vector from being a row vector (horizontal) into a column vector (vertical).

I did the same transpose command with a matrix, and you can see all the rows and columns have switched:

(b) Matrix Arithmetic Operators (aka Matrix Operators)

Note that only the last three operators change syntax for array operations

Arithmic operators include addition (+), subtraction (-), multiplication (*), division, and exponentiation (^). These are divided into two sections – Matrix Operators versus Array Operators.

List of arithmetic operators and the conditions they are valid under. Note that division is just as valid as multiplication in this case

Matrix Operations follow linear algebra formulas, so it won’t multiply, divide, or exponentiate arrays the way you think it would, whereas Array Operations are done element-by-element, meaning the operation is applied to each number within the vector or matrix. Here I have created vectors A and B, and done some of these operations on them:

For addition and subtraction, the first position in each vector is combined, then the second position, and so on. For example, to add the two vectors, the numbers in the first positions of both vectors A and B are added together (1 + 1 gives 2 in the output vector) and so on for each operation:

Vector Addition of A+B
Vector Subtraction of A-B

For multiplication, you can multiply a vector or matrix by a scalar value (aka this means a number) or another matrix/vector (eg. if I have vector B I could multiply it by vector A), provided they have the same number of rows and columns as one another.

For exponentiation, it only works if you have a square (3×3, 4×4, 5×5, etc) matrix, but you can raise it to any scalar exponent (aka only a number), and it will do the cross product with itself (A^2 means A*A in this case):

Matrix Multiplication and Matrix Exponentiation

(c) Array Arithmetic Operators (aka Array Operators)

Array Operators are done element-by-element. This means that each value in the array has the operation done on it. When doing certain operations on arrays, namely multiplication, division and exponentiation, there needs to be a dot (.) before the operators. Take a look at this table:

The dot indicates that each element in one array will multiply or divide with its respective element in the other array. This is the same as what MATLAB did above with adding and subtracting earlier, but we just need to add this extra dot when doing these specific operations. Note this image below which shows how operators would work on vectors U and V.

Here are some examples. Notice how I have the dot before the * / ^ signs in A.*B, A.\B, and A.^B:

Vector Multiplication (Element by Element)
Vector Division (Element by Element)
Vector Exponentiation (Element by Element)

(d) Sum and Product of Elements

We can take the sum or the product all the elements within a vector or matrix. To do this, use sum( ) or prod( ), respectively. Here’s an example where I’ve created 2 arrays, then taken the sum and product of each. MATLAB takes the sum or product of each column, then return one output vector, as shown in the examples below:

(e) Size

We can check the size (rows by columns) of a matrix (or just the length of the row or column) of a vector. To do this, we use the size( ) command. Here’s an example of two arrays, where MATLAB returns two numbers in the output. These numbers stand for row and column. In the first array, the answer was 1 and 5. The second array output was 2 and 4. This means that the size of the respective arrays were 1×5 and 2×4.

(f) Sort

We can sort the values in a vector or matrix by highest to lowest, or vice versa. To do this, use the sort( ) command, and MATLAB will sort the elements of the matrix in increasing order. If A is a matrix, then each column is treated as a vector and sorted accordingly. Note that sort(A,1) is the same as sort(A). We can also use sort(A,2), where each row will be treated as a separate vector and sorted accordingly, rather than doing it by columns as default.

The direction of sorting can also be specified – sort(array, direction) for a matrix A could be sort(A, ‘ascend’) or sort(A, ‘descend’).

Here’s an example. I’ve created a matrix A, then used sort(A) and sort(A,1). Both gave the same answer, and each column was sorted individually so the higher number is on top. sort(A,2) sorts each row in increasing order rather than each column.

Now trying to sort the values (by default when they’re sorted by column) in ascending and descending order, this is what we get. Note that the words ‘ascend’ and ‘descend’ need the single quotes around them, or you’ll get the same error I did at first:

(g) Magic

Magic is used to give a square matrix with the size you input. It will create random numbers from 1 to n^2 to fill within the matrix. n will be the number you put into the command. For example, if you do magic(3), then the matrix will be filled with random numbers from 1 to 9 (since 3^2 is 9). Note: It won’t work with the number 1 – it will just output the same number back to you. Let’s try it with 4. This is the syntax:

This is the output. The matrix is filled with numbers from 1 to 16:

(h) Repmat

Repmat is used to give a repeating matrix from one that you specify, with a specified number of rows and columns. You can either have the same number repeating, or you can have a specified matrix to repeat. Here are examples of both:

Say we want to repeat the number 8 within a matrix with 2 rows and 5 columns. You would use the syntax repmat(number to repeat, number of rows, number of columns). I have used repmat(8,2,5) because I want the number 8, in 2 rows and 5 columns.

This is the output:

Now say we instead created a matrix A, and this is the matrix we would like to repeat.

If we wanted to repeat this 3 times, we can use the syntax repmat(matrix name, number of repeats). I have used repmat(A,3) to indicate that I want it repeating three times. MATLAB will then make it repeat three times in the rows and columns both, so you will have the original matrix repeat nine times in this larger matrix.

(i) Diag

Diag will put numbers down the diagonal of a matrix. You can specify a vector which will be used down the diagonal, or specify whether you want that vector to appear above or below the main diagonal. Let’s take a look at both examples.

Say we have the matrix [1 2 3] and want to place it down the diagonal of a matrix. We will use the syntax diag([vector]), where the word [vector] is replaced with the vector [1 2 3]. Notice how this vector is down the diagonal, and there are zeroes in all the other spots:

If I wanted this vector to appear above the main diagonal, I could use the syntax diag([vector], 1), where I replace the word [vector] with [1 2 3]. Notice how the matrix has become bigger so that this vector could fit above the main diagonal. Every time you want to move these numbers up or down by a diagonal, you will need to increase or decrease the number in the brackets starting at 0. For example, to move this vector up one diagonal from the main one, I use diag([vector], 1). If I wanted to move it up another diagonal, I would use diag([vector], 2). To move it one below the diagonal, I would use diag([vector], -1), and so on.

(j) Reshape

This command is used to reshape the size of a matrix. This does not add or remove rows or columns, but it can change the layout. For example, rather than having a 1-by-4 vector, you can make it a 2-by-2 matrix.

Say we have the following 1-by-4 vector:

Now to change this into a 2-by-2 matrix, use the reshape(variable,[row,column]) command. Replace [row,column] with the number of rows and columns you want, and replace variable with the variable storing the vector or matrix you want to reshape. Now we have a 2-by-2 matrix:

Dot and Cross Products

The dot and cross products are usually taught in physics or mechanics courses. To learn more about the equations behind the dot and cross products, check out this lesson: linked here. I won’t go into detail on the math behind these, because it’s discussed in the lesson linked above, and MATLAB handles it for us anyways – we just have to know the syntax to type in!

In math, dot product (the top one) and cross product (the bottom one) look like this:

But in MATLAB, when we try to use these operations (* or X) it doesn’t do the actual dot and cross product, although it may output a different answer rather than an error.

So what are the dot and cross products? The dot product returns a number that describes how much of one vector is in the direction of the other (remember that vectors have directions). For example, if we are pushing a box, we have both the force (a vector) used to push the box, and the displacement of the box (a vector as well) included in the problem. Doing the dot product of these is the physics equation for work, and gives us the work done on the object by a specific force. We won’t get too much into the physics of it right now, but there are many more applications. It is also sometimes called the scalar product, because it gives a scalar answer.

To do the dot product, use dot(A,B), where A and B are the two arrays that the dot product is being performed on. A and B must be the same size (same number of rows and columns) for this to work! Here’s an example, where I have created two vectors of the same size, A and B. Of course, they don’t have to be called A and B – name them anything you’d like, but just make sure to type in the correct names of the variables when you type the syntax for the dot product. The answer it gives me here is 64:

In this second example, I have created vectors A and B again, but they are not the same size. Notice how I got an error mentioning this issue in red:

In this third example, I did the dot product with two matrices, and it still worked:

Now let’s take a look at the cross product.

The cross product gives an output vector that is perpendicular (aka orthogonal) to the two arrays that the cross product was originally performed on. If the two arrays are parallel, then the cross product is zero. Because the output is a vector, the cross product is also sometimes called the vector product.

To do this in MATLAB, use the command cross(A,B), where A and B are the two arrays you are taking the cross product of. They must have a length of 3 exactly (either 3 rows or 3 columns) for it to work.

In this first example, I used two vectors with one row each to work the cross product on. Notice the error asked that the vectors need to be of “length 3.” This means that either the rows or columns need to have only 3 elements within them.

In this second example, both matrices are now 2 rows by 3 columns (2×3 matrices). This time, the cross product worked to output a new matrix!

In this third example, I have two vectors of length 3. The cross product worked here as well.

In this fourth example, there are two 3×3 matrices that give the cross product. Note that cross(A,B,1) or cross(A,B) does the same thing. By default, MATLAB treats each column as a vector and does the cross product. This is what it refers to with the ‘1’ in the brackets above.

In the last example, if I change the length of the vectors to 4, it won’t work. This is because cross product does not work if the length of the vector is not 3.

So now that we’ve seen how the cross(A,B) command works, in that it needs to have at least either the rows or the columns be exactly of length 3, we can also do cross(A,B,dim). This evaluates the cross product along a specific dimension, as shown below (taken from Mathworks.com):

Because the default is using ‘1’ for the dimension, where each column is treated as a vector, the other option is to use ‘2’ in place of the dimension, where each row is treated as a vector instead. Continuing the example above, cross(A,B,1) gives the same answer I had shown above. Using cross(A,B,2) gives a different answer: