How to insert a row into a matrix in Matlab and Octave
To insert a row in an array without replacing the other existing rows in Matlab / Octave type [M; V]
[M ; V]
- The parameter M is the matrix
- The parameter V is a vector with the values of the new row
This command adds the new row to the matrix.
Examples
Example 1
Define a 3x3 matrix
>> M = [ 1 2 3 ; 4 5 6 ; 7 8 9 ]
M =
1 2 3
4 5 6
7 8 9
Define a row vector
>> V = [ 0 1 0 ]
To insert the new row at the bottom of the matrix type [M ; V]
>> [M;V]
ans =
1 2 3
4 5 6
7 8 9
0 1 0
Example 2
To insert the new row as the first row of the matrix type [V ; M]
>> [V;M]
ans =
0 1 0
1 2 3
4 5 6
7 8 9
Example 3
To insert the new row in an intermediate position in the matrix, type [M(1:2,:);V;M(3:end,:)]
>> [M(1:2,:);V;M(3:end,:)]
ans =
1 2 3
4 5 6
0 1 0
7 8 9
In this case the new line is after the first two lines.
Note. The first parameter M (1: 2, :) extracts the first two rows of the matrix. The second parameter V is the vector of the new row to insert. The third parameter M (3: end, :) extracts the last rows of the array.