Inserting a column in an matrix array

2 ビュー (過去 30 日間)
Bartosz Bagrowski
Bartosz Bagrowski 2022 年 5 月 17 日
回答済み: Monica Roberts 2022 年 5 月 17 日
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 Center および File ExchangeCreating 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