Matrices: Matrices in MATLAB
Selection of components and assignment of values
Selection of components and submatrices You can select components of arrays in various ways. We give a few examples showing that indexing starts at (1, 1) and that there are smart ways to create submatrices. The last command in the session below illustrates that you can consider a matrix in MATLAB as a column vector obtained by stacking vertically all the columns from left to right; you can therefore designate a single element with one index.
>> M = [2:5; 6:9; 10:13]
M =
2 3 4 5
6 7 8 9
10 11 12 13
>> M(2,3) % a single element
ans =
8
>> M(:, 3) % third column
ans =
4
8
12
>> M(1,:) % first row
ans =
2 3 4 5
>> M(1, 2:end) % first row, all except first column
ans =
3 4 5
>> M(1:2, 1:2) % submatrix
ans =
2 3
6 7
>> M(6) % selection of component by considering matrix as column vector
ans =
11
Selection via logical expressions You can also use logical indexing (with zeros and ones) to select matrix elements. You need relational operators for this, such as the ones in the table below. Besides logical indexing you can also use the find
instruction to find suitable indices for a logical expression.
== | equal to | ~= | not equal to |
< | less than | > | greater than |
<= | less than or equal to | >= | greater than or equal to |
>> M = [2:5; 6:9; 10:13]
M =
2 3 4 5
6 7 8 9
10 11 12 13
>> M>7 % matrix entry 1 if the condition is met, 0 otherwise
ans =
3×4 logical array
0 0 0 0
0 0 1 1
1 1 1 1
>> M(ans) % columnwise selection of components
ans =
10
11
8
12
9
13
>> find(M<8) % selection of indices via find command
ans =
1
2
4
5
7
8
10
>> M(ans) % columnwise selection of components
ans =
2
6
3
7
4
5
Assignment Components to which you refer can also be assigned new values.
>> M = [2:5; 6:9; 10:13]
M =
2 3 4 5
6 7 8 9
10 11 12 13 >> M(3,4) = 17 % change of one matrix entry
M =
2 3 4 5
6 7 8 9
10 11 12 17
>> M(:,4) = 1 % assign all entries in fourth column the value 1 M =
2 3 4 1
6 7 8 1
10 11 12 1 >> M(1,:) = [] % remove the first row M =
6 7 8 1
10 11 12 1 >> M(:) = 0 % assign all matrix entries the value 0 M =
0 0 0 0
0 0 0 0
By assignments you can modify the the structure provided that you are left with a matrix. In the example below we give a matrix extra entries by assignment. By the way, this is not a recommended way to work. Pre-reserving ample space for components in a matrix structure through the zeros construction, followed by filling the matrix with values through assignments, is a better way to collect data in MATLAB experiments.
>> clear all
>> M = [2,4; 3, 5] % 2x2 matrix
M =
2 4
3 5
>> M(:,3) = [6; 7] % 2x3 matrix by assignment
M =
2 4 6
3 5 7
Change of shape You can change the shape from a vector or matrix. The following two examples illustrate this.
>> v = 1:6 % vector of length 6
v =
1 2 3 4 5 6
>> A = reshape(v, 3, 2) % 3x2 matrix
A =
1 4
2 5
3 6
>> B = reshape(A, 2, 3) % 2x3 matrix
B =
1 3 5
2 4 6