Inserting a column in an matrix array

1 view (last 30 days)
Bartosz Bagrowski
Bartosz Bagrowski on 17 May 2022
Answered: Monica Roberts on 17 May 2022
Hi guys,
I would like to write a code to insert the column insert a whole column in an array as in a following example:
q=[1 2 3 4, 5 6 7 8, 9 10 11 12, 13 14 15 16, 17 18 19 20];
for example:
i1=2
i2=4
I want to insert the second column after the fourth but I don't wan't to see the second one at the second place, so then I would have 1 3 4 2 columns in this order. Here in my code it inserts randomly picked column but then the column is in both places and q new has one column more.
i=randsample(n,2) %randomly picking two columns
i1=i(1);
i2=i(2);
v=q(:,i(1));
qnew = [q(:,1:i(2)) v q(:,i(2)+1:end)]

Answers (1)

Monica Roberts
Monica Roberts on 17 May 2022
You could just delete the duplicate column you don't want anymore:
qnew = [q(:,1:i2) v q(:,i2+1:end)];
if i1<i2
qnew(:,i1)=[]
else % original column shifted when added new column
qnew(:,i1+1)=[]
end

Categories

Find more on Environment and Settings in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!