Inserting a column in an matrix array

2 次查看(过去 30 天)
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)]

回答(1 个)

Monica Roberts
Monica Roberts 2022-5-17
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

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by