11.3: Matrix Indexing
- Page ID
- 85029
Let’s look at how we can reference parts of a matrix.
Consider the matrix A = [1 2 3 4;5 6 7 8]. There are actually two ways to view this matrix, either as a rectangular array of 2 rows and 4 columns, or as a list of 8 elements. Suppose we wanted to isolate the 7 in the matrix A and store it as the variable temp. First, we can think of the 7 as being located in the second row and third column. In this case, we can type:
>> A = [1 2 3 4;5 6 7 8];
>> temp = A(2,3)
with the result being:
temp =
7
Second, we can think of 7 as being one of the eight elements total. But, it is crucial to realize that we count elements in this way using a “column precedence.” This means that we count, one at a time, down the columns. This means that we can think of 7 as being located in the 6th entry, or:
>> temp = A(6)
also gives the result:
temp =
7
For completeness, in the last example, if we think of A as a matrix:
A(1,1) = 1 A(1,2) = 2 A(1,3) = 3 A(1,4) = 4
A(2,1) = 5 A(2,2) = 6 A(2,3) = 7 A(2,4) = 8
or, thinking of A as a vector:
A(1) = 1 A(3) = 2 A(5) = 3 A(7) = 4
A(2) = 5 A(4) = 6 A(6) = 7 A(8) = 8
If we wanted to store the entire first row of A in the variable firstrow, we would say that we want “all four columns of the first row.” This suggests that we can use the colon operator to shorten our work. Namely,
>> firstrow = A(1,1:4)
which gives
firstrow =
1 2 3 4
But, there’s an even shorter way to do this! If the colon doesn’t have a start and end value, it simply lists all possible values! Namely,
>> firstrow = A(1,:)
also gives
firstrow =
1 2 3 4
Ok, now what if we wanted the first row, but not the element in the first column? There are two ways to do this. First, we can use the colon as:
>> mostoffirstrow = A(1,2:4)
which gives
mostoffirstrow =
2 3 4
But, what if the matrix changes and we don’t know how big A has changed to? Those sneaky programmers at Mathworks have a work around:
>> mostoffirstrow = A(1,2:end)
also gives
mostoffirstrow =
2 3 4
"Hilbert matrix" rows
Consider the 5 x 5
H5 = [1 1/2 1/3 1/4 1/5;
1/2 1/3 1/4 1/5 1/6;
1/3 1/4 1/5 1/6 1/7;
1/4 1/5 1/6 1/7 1/8;
1/5 1/6 1/7 1/8 1/9];
By referencing H5, create a matrix that consists of the 2nd and 3rd rows of H5 (Do not simply retype the entries).
- Answer
-
Add texts here. Do not delete this text first.
.