lettura simple

How to add a row or column to a matrix in Octave

In this lesson I'll explain how to add a row or a column in a matrix using Octave by doing two practical examples.

How to add a column

Type M = [1 2 3; 4 5 6] to create a 2x3 rectangular matrix with two rows and three columns.

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

Create a column vector V=[7;8] with two elements arranged on two lines.

Vector V must have the same number of rows as the matrix.

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

To add a new column V to the matrix M type M=[M V]

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

You added a new column in the matrix

Now the matrix is a 2x4 rectangular matrix with two rows and four columns.

Note. Alternatively you can type M = [ M [7;8] ] without creating the V column vector. The final result is the same.

How to add a row to the matrix

Type M = [1 2 3; 4 5 6] to create a 2x3 rectangular matrix with two rows and three columns.

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

Then type V=[7 8 9] to create a row vector with three elements.

The number of elements in the vector V must be equal to the number of columns in the matrix M.

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

Type M = [M ; V] to add a new row V to matrix M.

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

This way you have added a new row to the matrix

Now the matrix M is a 3x3 matrix with three rows and three columns.

Note. Alternatively you can type M = [ M ; [7 8 9] ] with the elements of the new row in square brackets without creating the row vector. The result is the same.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin