How to insert a column in a matrix of Matlab/Octave
To add a column in a matrix without replacing other existing columns in Matlab/Octave type [M V]
[M V]
- Parameter M is the name of matrix
- Parameter V is a column vector
This command outputs the array with a column added.
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 column vector
>> V = [ 10; 11 ; 12 ]
V =
10
11
12
To append a column of the matrix type [M V]
[M V]
The command returns a 3x4 matrix with three rows and four columns
The vector is added as the last column of the matrix
ans =
1    2    3   10
4    5    6   11
7    8    9   12
Example 2
To insert a column as the first column of the matrix type [V M]
>> [V M]
The command returns a 3x4 matrix
The new column is added as the first column
ans =
10    1    2    3
11    4    5    6
12    7    8    9
Example 3
To add a column after the second column of the matrix, type [M(:,1:2) V M(:,3:end)]
>> [M(:,1:2) V M(:,3:end)]
The result is a 3x4 matrix
The command adds a new intermediate column to the matrix without replacing the other columns
ans = 
1    2   10    3
4    5   11    6
7    8   12    9




