lettura simple

Adding a row or a column to a matrix in Matlab

In this lesson, I'll show you how to add a row or a column to a matrix in Matlab with two practical examples.

How to add a column to the matrix

Create a 2x3 matrix with two rows and three columns.

>> M = [1 2 3; 4 5 6]
M =
1 2 3
4 5 6

Then create a column vector with two rows.

The vector should have the same number of rows as the matrix.

>> V=[7;8]
V =
7
8

Now type the command M=[M V] to add the column to matrix M.

>> M=[M V]
M =
1 2 3 7
4 5 6 8

You have added a column to the matrix.

The result is a 2x4 matrix with two rows and four columns.

Note. Alternatively, you could have also written the command M = [ M [7;8] ] without creating the column vector, indicating the elements of the column to be added within the innermost square brackets. The final result is the same.

How to add a row to the matrix

Create a rectangular 2x3 matrix with two rows and three columns.

>> M = [1 2 3; 4 5 6]
M =
1 2 3
4 5 6

Then create a row vector composed of three elements.

The number of elements in the vector should be equal to the number of columns in the matrix.

>> V = [ 7 8 9 ]
V =
7 8 9

At this point, type M = [M ; V] to add the row vector to the matrix.

In this case, M and V are separated by a semicolon, which is equivalent to a line break on a new row.

>> M = [M ; V]
M =
1 2 3
4 5 6
7 8 9

You have added a row to the matrix

The final result is a 3x3 matrix with three rows and three columns.

Note. Alternatively, you could have typed the command M = [ M ; [7 8 9] ] by writing the elements of the new row without creating a row vector. The final result is the same.

In this lesson, you have learned how to add a row or a column to a matrix in Matlab.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin