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 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