10.1: Matrices
- Page ID
- 84545
A matrix is a two-dimensional version of a vector. Like a vector, it contains elements that are identified by indices. The difference is that the elements are arranged in rows and columns, so it takes two indices to identify an element.
Creating a Matrix
A common way to create a matrix is the zeros
function, which returns a matrix with the given size filled with zeros. This example creates a matrix with two rows and three columns.
>> M = zeros(2, 3)
M = 0 0 0
0 0 0
If you don’t know the size of a matrix, you can display it by using whos
:
>> whos M
Name Size Bytes Class Attributes
M 2x3 48 double
or the size
function, which returns a vector:
>> V = size(M)
V = 2 3
The first element is the number of rows; the second is the number of columns.
To read an element of a matrix, you specify the row and column :
>> M(1,2)
ans = 0
>> M(2,3)
ans = 0
When you’re working with matrices, it takes some effort to remember which index comes first, row or column. I find it useful to repeat “row, column” to myself, like a mantra. You might also find it helpful to remember “down, across” or the abbreviation RC as in “radio control” or RC Cola.
Another way to create a matrix is to enclose the elements in brackets, with semicolons between rows:
>> D = [1,2,3 ; 4,5,6]
D = 1 2 3
4 5 6
>> size(D)
ans = 2 3
Row and Column Vectors
Although it’s useful to think in terms of numbers, vectors, and matrices, from MATLAB’s point of view everything is a matrix. A number is just a matrix that happens to have one row and one column:
>> x = 5;
>> size(x)
ans = 1 1
And a vector is a matrix with only one row:
>> R = 1:5;
>> size(R)
ans = 1 5
Well, some vectors have only one row, anyway. Actually, there are two kinds of vectors. The ones we’ve seen so far are called row vectors, because the elements are arranged in a row; the other kind are column vectors, where the elements are in a single column.
One way to create a column vector is to create a matrix with only one element per row:
>> C = [1;2;3]
C =
1
2
3
>> size(C)
ans = 3 1
The difference between row and column vectors is important in linear algebra, but for most basic vector operations, it doesn’t matter. For example, when you index the elements of a vector, you don’t have to know what kind it is:
>> R(2)
ans = 2
>> C(2)
ans = 2
The Transpose Operator
The transpose operator, which looks remarkably like an apostrophe, computes the transpose of a matrix, which is a new matrix that has all of the elements of the original, but with each row transformed into a column (or you can think of it the other way around).
In this example D
has two rows:
>> D = [1,2,3 ; 4,5,6]
D = 1 2 3
4 5 6
so its transpose has two columns:
>> Dt = D'
Dt = 1 4
2 5
3 6
What effect does the transpose operator have on row vectors, column vectors, and numbers?