Inserting a column in an matrix array

1 visualización (últimos 30 días)
Bartosz Bagrowski
Bartosz Bagrowski el 17 de Mayo de 2022
Respondida: Monica Roberts el 17 de Mayo de 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)]

Respuestas (1)

Monica Roberts
Monica Roberts el 17 de Mayo de 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

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Productos


Versión

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by