
Extracting one or more columns from a matrix in Matlab
In this lesson, I will explain how to extract one or more columns from a matrix (two-dimensional array) when using Matlab.
To illustrate this point, let me provide an example.
Create a 3x3 matrix in the Matlab session.
>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9
This is a square matrix because it has the same number of rows and columns.
To extract the first column of the matrix, type M(:,1)
- In the first parameter in parentheses, insert the colon symbol : to select all the rows in the matrix
- In the second parameter, enter the integer 1 to select the first column of the matrix
>> M(:,1)
This way, you will extract all the elements that are present in the first column of the matrix.
ans =
1
4
7
Now, type M(:,2) to extract the second column of the matrix.
In this case, you are indicating the number 2 in the second parameter because you want to select all the elements in the second column of the matrix.
>> M(:,2)
ans =
2
5
8
Finally, type M(:,3) to extract the third column of the matrix:
>> M(:,3)
ans =
3
6
9
If you want to extract only certain rows of a column, insert the range of rows you want to select in the first parameter.
For example, type M(1:2,3) to extract only the first two rows of the third column:
>> M(1:2,3)
ans =
3
6
When the rows you want to select are not contiguous, insert the list of rows in the second parameter between square brackets, separating them with a comma or space.
For example, type M([1 3],2) to extract the first and third row of the second column:
>> M([1 3],2)
ans =
2
8
In Matlab, you can also extract two or more columns from a matrix by specifying the range of columns to select in the second parameter of the command.
For example, M(:,1:2) extracts the first two columns of the matrix named "digita":
>> M(:,1:2)
ans =
1 2
4 5
7 8
To extract non-contiguous columns, you can specify a list of columns to extract in the second parameter, enclosed in square brackets and separated by a space or comma.
For example, type M(:,[1 3]) to extract the first and third columns of the matrix:
>> M([1 3],:)
ans =
1 3
4 6
7 9
This command allows you to extract two or more columns of a matrix even if they are not contiguous.