lettura simple

Extracting one or more rows from a matrix in Matlab

In this lesson, I will explain how to extract one or more rows from a matrix (two-dimensional array) in Matlab.

Here's an example.

Create a 3x3 matrix with three rows and three columns.

>> 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, which is 3x3.

a 3x3 matrix

To extract the first row of the matrix, type M(1,:)

  • The first parameter (1) indicates the first row of the matrix,
  • The second parameter (:) is the colon symbol that means "take all columns of the matrix."

>> M(1,:)

extract the first row of the matrix

This will extract all elements of the first row of the matrix.

ans =
1 2 3

Now, to extract the second row of the matrix, type M(2,:).

You need to specify 2 as the first parameter.

>> M(2,:)
ans =
4 5 6

This will extract the second row of the matrix.

extract the second row of the matrix

Finally, to extract the third row of the matrix, type M(3,:)

This command will only extract the third row of the matrix.

>> M(3,:)
ans =
7 8 9

extract the third row of the matrix

If you want to extract only some columns of a row, write the range of columns to consider in the second parameter.

For example, type M(3,1:2) to extract only the first two columns of the third row.

>> M(3,1:2)
ans =
7 8

extract the first and the second row of the matrix

When the columns to extract are not adjacent, indicate the list of columns within square brackets, separating them with a comma or a space.

For example, type M(2,[1 3]) to extract the first and third column of the second row.

>> M(2,[1 3])
ans =
4 6

extract the first and the third column in the second row of the matrix

To extract two or more rows from the matrix, write the list or range of rows to consider.

For example, to extract the first two rows of the matrix, type M[1:2,:]

>> M(1:2,:)
ans =
1 2 3
4 5 6

extract the first two rows

If you want to extract the first and third row of the matrix, type M([1 3],:)

>> M([1 3],:)
ans =
1 2 3
7 8 9.

extract the first and third rows of the matrix

This way, you can extract one or more rows from the matrix, even if they are not adjacent to each other.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin