MATLAB: Inserting a column in a matrix without deleting any column

MATLABmatrix manipulation

Hi,
I am wondering of there is a function that enables me to insert a column in a matrix (similar to insert column in excel) without replacing any existing column. For example I have Matrix "A" which is 4×4 and I want to insert a vector "B" after the second column of "A" in order to obtain "A" 4×5 where the 3rd column of "A" is vector "B"

Best Answer

Suppose you have:
>> A=reshape(1:16,4,4)
A =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>> B=(17:20)'
B =
17
18
19
20
Then you could obtain the desired matrix C by:
>> C = [A(:,1:2) B A(:,3:4)]
C =
1 5 17 9 13
2 6 18 10 14
3 7 19 11 15
4 8 20 12 16
So you take the first two columns of A concatenate the column B and then concatenate the last two columns of A.
You can generalize this a bit into:
>> D = [A(:,1:N) B A(:,N+1:end)]
Where N then stands for "insert B after the Nth column".