CHAPTER 4
We have now come to arguably the most important chapter in the book. Remember, MATLAB stands for MATrix LABoratory, so work with matrices is central to just about everything that goes on in MATLAB. In this chapter, we get to look at the way matrices are created and manipulated, and some common operations that apply to them.
Before we get started, remember that all variables in MATLAB are, in fact, arrays. What I mean is that when you write x=5, you may as well have written x=[5], and both of these effectively imply a 1×1 array.
In our discussions, we’ll use the terms array and matrix interchangeably. We will, however, use the term vector to mean a one-dimensional array. In this case we’ll also use the term row vector to mean a horizontal array that takes up one row:
123
and the term column vector to mean an array that takes up one column:
456
The simplest way to initialize an array is to declare a variable and initialize it using square brackets, separating the elements with spaces and/or commas:
>> x = [1, 2 3 4] |
What we’ve got is a row vector of 4 elements. If we want a column vector instead, we write roughly the same thing, but instead of spaces we separate the entries with semicolons:
>> y = [1;2;3;4] |
An entirely different way of initializing arrays is to use the colon operator. This operator lets you define arrays containing sequences of values. For example:
>> z = 1:10 |
The above has created a row vector with elements 1 to 10. Curiously enough, this approach also works with strings, so you can, for example, declare an array going from a to z, which will yield… you guessed it, a string with all the characters from a to z!
>> 'a':'z' |
Using the column operator, you can specify not only the start and end of the range of values, but also the step size. For example, here we generate all odd numbers from 1 to 15:
>> 1:2:15 |
Note that if you want a decreasing set of values, the step size needs to be negative, so if you want the above numbers in descending order, you need to write 15:-2:1.
>> 15:-2:1 |
And that’s not all. There is another command for creating a set of values in a specific range. The function linspace subdivides a range into several points (100 by default). The third parameter to the function lets you define how many points you want:
>> linspace(0,1,11) |
In this call, we’ve generated 11 equally spaced points on a [0; 1] range.
Tip: When using linspace, you typically want to have the number of points to be one more than the number of parts you want to divide the range into. For example, if you want to split a range into 100 parts, consider specifying 101 points.
Now let’s move on to two-dimensional arrays. Such an array can be initialized with a combination of spaces. For example, to create the matrix 1234 we write:
>> g = [1 2;3 4] |
Having made a matrix, we can use the size function to take a measurement of its dimensions:
>> size(g) |
Once again, MATLAB has special functions for creating two-dimensional arrays. First of these is the zeros function, which creates a zero-initialized matrix:
>> zeros(3,2) |
Note that, when specifying dimensions, you first specify the number of rows (3) and then the number of columns (2). Had you specified only a single argument, that argument would be taken for both dimensions – in other words, zeros(3) creates a 3x3 array. The function zeros also has its counterpart called ones. I leave it to the reader to figure out what kind of matrix it creates. And, similarly to these, the functions inf, nan, and rand, when provided size arguments, create matrices correspondingly filled with infinity, NaN, and random values.
Jumping ahead a little bit, it is important to realize that functions such as zeros can create arrays of any dimensions. We have made a 2D array above, but we could easily create a 3D array by providing an array of dimensions as an array as the first and only argument to the function:
>> zeros(2,3,2) |
This code effectively creates a 2×3×2 array. Don’t worry; we will get to multi-dimensional arrays very soon.
Meanwhile, here is another special array-building function called eye, which creates an identity matrix:
>> eye(3) |
Invoked with a single argument, it has created a square 3×3 array for us. Had we specified two arguments, it would have created a rectangular array that would have zeroes in all places except the diagonal.
Now that we know how to create arrays, let us discuss ways of manipulating them. Let us make an array from 1 to 100. (Note that we have terminated the statement with a semicolon here to suppress the output. Had we not done this, we would get 100 numbers in the command window.)
>> x=1:100; |
To get a single element of the array, you just write the name of the array followed by an index of the element. For example, to get the first element of the array x we write:
>> x(1) | ||
To get all elements from position 5 to position 10, we can simply write:
>> x(5:10) |
What we end up with is a brand new array of six elements corresponding to positions 5 to 10 in the original array.
Note: Array indices in MATLAB start with 1, not with a 0.
There is also a special variable end that you can use to indicate the last element of the array. For example, to get the last ten elements of the array, we can write:
>> x(end-9:end) |
It’s also possible to filter elements of an array by specifying a precondition. For example, here’s a way of taking all odd values from 1 to 10:
>> x = 1:10 |
There are quite a few things happening in this example. First of all, it’s worth noting that mod is a vectorized function, meaning that for each of the elements in the input array it will generate as many in the output. The operator == is also perfectly happy to work in a vectorized manner, being applied to each element of mod’s output in turn. Finally, since the end result of a comparison is a logical value, this illustrates another way of indexing into an array: by providing a set of true/false values as indices, we filter the array, leaving only those elements for which the corresponding parameter value is true.
As you may have guessed, not only can we access elements of the array, we can modify them too. Changing a single element is easy—you just write x(10)=123 and that’s your 10th element changed. But, interestingly enough, we can also change a subset of an array by providing a new array (obviously, the sizes must match). For example, to reverse the order of the first five elements of our array, we can write
>> x(1:5)=5:-1:1 |
This operation essentially creates a range of values from 5 to 1 with a step of -1 and then places those values in positions 1 through 5 of the original array.
Manipulation of 2D arrays follows very similar ideas. Consider the following array:
>> x = [1 2;3 4] |
I can index its elements using either two indices (corresponding to its row and column) or I can use just a single index, in which case the array is traversed in column order (meaning we first traverse the first column top-to-bottom, then the second, and so on):
>> x(2,1) |
You can also get the whole row or the whole column of a 2D (or indeed N-d, where N>1) array by simply replacing the specifier for the other dimensions with a : (colon) operator, which is the operator that’s used to indicate a “don’t care” or “give me everything” value. For example, to get the first row, we write:
>> x(1,:) |
This invocation essentially says “give me something from row 1, and all columns.” And that’s exactly what you get. Needless to say, modifications to 2D arrays happen in just the same way as for 1D arrays, so to replace the first column with the values [5, 6] you can write:
>> x(:,1) = [5;6] |
When it comes to removing elements from the array, one possibility is to set the elements you want to remove to [], which is an empty array:
x = |
It’s also possible to take the diagonal of a matrix with the diag function. Here is a rather convoluted way of creating a column vector filled with 1s:
>> diag(eye(3)) |
The diag function simplifies work with diagonal matrices and actually works both ways: not only can you take the diagonal of an existing matrix, you can turn a vector with a matrix containing zeros in all elements except the diagonal:
>> diag([1 2 3]) |
To illustrate the idea of sorting the elements in the array, I will make a 5×5 magic square using MATLAB’s magic function:
>> z = magic(5) |
Just in case you’re wondering, a magic square has a property in which all its rows and columns have elements that add up to the same number. We aren’t going to exploit this property for our demonstrations, though—instead, let’s try sorting the array. To sort each of the columns in the array, we can simply use z as an argument to the sort function:
>> sort(z) |
Now each of the columns appears in order. If we wanted to sort each of the rows, however, we would need to explicitly specify the dimension to sort on in our call to sort: the second parameter value of 1 means rows, 2 – columns.
>> sort(z,2) |
And this gives us a matrix where each row’s values appear in ascending order.
Now, let’s say we’ve got two simple arrays:
>> x = [1 2]; |
We can merge these two arrays into a single array. To concatenate these two arrays together, we simply make a new array with x and y being featured as its elements:
>> [x y] |
Note that, in the last example, I have included the original arrays in the new array more than once. This is perfectly legal, and simply causes repetition of the contents of the source arrays.
Now, suppose you want enlarge an array. How would you do it? Well, the simplest way is to assign an element of the matrix that doesn’t yet exist—this immediately reshapes the array to accommodate the new value:
>> whos x |
As you can see from the output, a 1×2 array was magically resized into a 3×3 array when a new element was added.
If you need to shrink the array, simply take a slice of it! For example, to get back to the original array, all I need to do is take the first two column elements of the first row:
>> x(1,1:2) |
MATLAB also has a set of very specific matrix operations, such as the ability to rotate a matrix 90 degrees:
>> z = eye(3); |
Last, but certainly not least, MATLAB has a reshape function. This function takes an array as if it were one-dimensional by iterating its dimensions, and then reshaping the array into as many dimensions as you specify. Naturally, the number of elements in the original and requested arrays must match:
>> x = magic(4); |
This piece of code, for example, takes a 4×4 magic square and reshapes it into a 2×8 array. Likewise, we could easily reshape the square into, e.g., a 1×16 array or a 2×4×2 array.
As with the reshape function, it’s also possible to turn a matrix into a column vector by addressing its elements with a single colon:
>> x = magic(2) |
Of course, this shouldn’t be particularly surprising: we already mentioned that multi-dimensional arrays can be indexed with a single value, so the result of getting all the values should not be unexpected.
Transposition is a very common matrix operation. Essentially, it reflects the matrix along the diagonal, so each element swaps its row and column positions. Strictly speaking, MATLAB has a transpose function defined for this purpose, but it is much easier to use a single dash (') for the exact same purpose (assuming non-complex data):
>> x = [1 2;3 4] |
Transposition is also useful for defining column vectors, since the x:y notation gives you a row vector by default:
>> (1:5)' |
Note the use of round brackets above—the ' operator has higher precedence than :, so you cannot write 1:5' because it effectively means 1:5'.
Another common operation is matrix inversion, which, given a matrix X gives you a matrix Y satisfying the relation YX=I (where I is the identity matrix, eye). The inverse matrix is found by either using the inv function or taking the original matrix to the power of -1:
>> x = [-1 1;0 1]; |
Elementwise operators are central to working with matrices in MATLAB. The best way to illustrate what they are for is with an example. Let us make two 2×2 matrices:
>> x=[1 2;3 4]; |
Now, the expression x*y implies multiplication of the two matrices according to linear algebra matrix multiplication rules (matrix dimensions should, of course, agree), but what if you just want each of the elements in x to be multiplied by the corresponding element in y (also known as a Hadamard product)? This is what elementwise operators are for. Essentially, all we have to do is put a period (.) in front of the multiplication operator, and here is what we get:
>> x.*y |
Elementwise operators are critical when working with any sort of data sets, and warrant additional examples. For instance, let’s say we put $100 into a bank account with a 5 percent interest rate paid annually. Now we want to know how much money we’ll have after 1..10 years. Our first temptation is to write something like:
>> 100*(1+0.05)^(1:10) |
But as you can see, we cannot take a scalar value to the power of an array—this operation simply doesn’t make any sense! What we need to do is replace the power operator with its elementwise version so that our scalar value gets raised to each of the powers in turn:
>> 100*(1+0.05).^(1:10) |
That’s much better.
One of the common uses of matrices is to use them to solve linear systems of equations. For example, consider this set of equations:
We can use matrices to represent this equation in the form of AX=B where A is the matrix of multipliers and B is the matrix of results:
MATLAB offers us the option to solve this system using the linsolve function. All we need to do is feed in the coefficients:
>> a = [1,1; 1,-1] >> b b = |
And now we’re going to meet another operator! We’ve already seen it as the back-division operator, but the array-specific \ (backslash) operator that also solves the equation AX=B can be more efficient by using Gaussian elimination without producing an inverse of the matrix. Thus, it’s faster than calculating inv(a)*b:
>> a\b |
In addition to ordinary matrices, MATLAB also supports sparse matrices. These are typically large matrices that have only a small percentage of non-zero entries. Sparse matrices are defined by providing the sparse function three arrays containing the coordinates of the element (one array for i, another for j) and the element values themselves:
>> i = [2,4,6]; |
A sparse matrix can also be turned into a proper, fully-specified matrix using the full function:
>> full(ans) |
One useful command for generally figuring out what is happening in an array is spy. This command lets you visualize the elements in an array on a graph, and is particularly useful for viewing sparse matrices. For example, spying on a 4×4 identity matrix gives us the following diagram:

Using the spy command on a 4×4 identity matrix.
As you may have guessed, dots represent non-zero elements while zeros do not get any dots. Note also the x and y coordinates, which correspond to matrix element positions. Oh, and make sure you don’t forget the arguments—if you just type spy, you’re in for a surprise.
As you may have guessed, arrays of dimensions higher than two cannot be efficiently represented on a two-dimensional computer monitor, but this doesn’t mean that we can’t work with them.
The simplest way to make a 3D array is to use one of the functions that takes array dimension parameters. For example, I can use the reshape function to create an array of eight values and shape them into a 2×2×2 array:
>> reshape(1:8, [2 2 2]) |
Note the visual representation: since a 3D array cannot be efficiently represented in 2D space, we get to see each of its 2D slices in turn.
Other MATLAB functions such as ones, zeros, and various random number generators also allow you to specify the dimensions of the matrix that’s being generated.
Another way of creating a matrix with more than two dimensions is to simply add an extra dimension to an existing 2D matrix. For example, you can start out with a 2×2 matrix:
>> x = [1 2;3 4] |
And now, you can simply “splice” another 2×2 matrix into x’s third dimension:
>> x(:,:,2) = [4 5;6 7] |
As you can imagine, the approaches outlined here work for higher dimensions as well.