In order to extract the (i, j)th entry from a matrix A, use parentheses:
>> A = [11:16; 21:26; 31:36; 41:46; 51:56] % see colon operator
A =
11 12 13 14 15 16
21 22 23 24 25 26
31 32 33 34 35 36
41 42 43 44 45 46
51 52 53 54 55 56
>> A(2, 5)
ans =
25
Given a row vector (a 1xn matrix) or a column vector (an nx1 matrix), you need only give one index:
>> v = 1:5
v =
1 2 3 4 5
>> v(3)
ans =
3
To access a block of elements (extracting submatrices and subvectors), a row vector index can be used in place of a integer index.
>> A([1 2], 3) % 3rd element of rows 1 and 2
ans =
13
23
>> A([1 2], [3 4 5]) % submatrix of the 1st and 2nd rows, and 3rd, 4th and 5th columns
ans =
13 14 15
23 24 25
>> v([1 3 4]) % subvector of the 1st, 3rd, and 4th elements
ans =
1 3 4
The colon operator can be used as well:
>> A(1:3, 1:3) % the upper left 3x3 submatrix
ans =
11 12 13
21 22 23
31 32 33
Instead of using numbers, you can use the keyword end to refer to the last element in the row or column:
>> A(3:end, 4:end) % the lower right 3x3 submatrix
ans =
34 35 36
44 45 46
54 55 56
>> A(end-2:end, end-2:end); % another way of doing the same thing
As well, you can use the short cut : to represent the entire row or column. That is, you can use : in place of 1:end:
>> A(3, :) % extract the 3rd row
ans =
31 32 33 34 35 36
The following shows how to extract the submatrix excluding the ith and jth columns:
>> i = 3; j = 2;
>> A([1:i - 1, i + 1:end], [1:j - 1, j + 1:end]) % remove 3rd row and 2nd column
ans =
11 13 14 15 16
21 23 24 25 26
41 43 44 45 46
51 53 54 55 56
Reversing the order of a vector is as easy as:
>> v(end:-1:1)
ans =
5 4 3 2 1
You can, if you want, refer to the same element multiple times, in any order, so the result is not necessarily a submatrix:
>> A(1, [3,2,1,5,3:end])
ans =
13 12 11 15 13 14 15 16
Logical Matrices as Indices
A logical matrix as an
index returns a column vector which selects all entries in the
matrix corresponding to true in the logical matrix.
>> A = [1 2 3; 4 5 6; 7 8 9]
A =
1 2 3
4 5 6
7 8 9
>> B = logical( [1 0 1; 1 1 0; 0 0 1] ) % must us the logical function
B =
1 0 1
1 1 0
0 0 1
>> A(B)
ans =
1
4
5
3
9