Matrices in Matlab 75
2.2 Matrices in Matlab
You can think of a matrix as being made up of 1 or more row vectors of equal length. Equivalently, you can think of a matrix of being made up of 1 or more column vectors of equal length. Consider, for example, the matrix 1 2 3 0 A = 5 −1 0 0 . 3 −2 5 0 One could say that the matrix A is made up of 3 rows of length 4. Equivalently, one could say that matrix A is made up of 4 columns of length 3. In either model, we have 3 rows and 4 columns. We will say that the dimensions of the matrix are 3-by-4, sometimes written 3 × 4. We already know how to enter a matrix in Matlab: delimit each item in a row with a space or comma, and start a new row by ending a row with a semicolon. >> A=[1 2 3 0;5 -1 0 0;3 -2 5 0] A = 1 2 3 0 5 -1 0 0 3 -2 5 0 We can use Matlab’s size command to determine the dimensions of any matrix. >> size(A) ans = 3 4 That’s 3 rows and 4 columns!
Indexing
Indexing matrices in Matlab is similar to the indexing we saw with vectors. The difference is that there is another dimension 2. To access the element in row 2 column 3 of matrix A, enter this command.
1 2
Copyrighted material. See: http://msenux.redwoods.edu/Math4Textbook/ We’ll see later that we can have more than two dimensions.
76 Chapter 2
Vectors and Matrices in Matlab
>> A(2,3) ans = 0 This is indeed the element in row 2, column 3 of matrix A. You can access an entire row with Matlab’s colon operator. The command A(2,:) essentially means “row 2 every column” of matrix A. >> A(2,:) ans = 5 -1
0
0
Note that this is the second row of matrix A. Similarly, you can access any column of matrix A. The notation A(:,2) is pronounced “every row column 2” of matrix A. >> A(:,2) ans = 2 -1 -2 Note that this is the second column of matrix A. You can also extract a submatrix from the matrix A with indexing. Suppose, for example, that you would like to extract a submatrix using rows 1 and 3 and columns 2 and 4. >>