ajj
ajj

Reputation: 127

MATLAB swap columns of two different matrices

Im using matlab and am having some difficulty. I am trying to swap the columns of one matrix (A) with the column of another matrix (B). For Example:

A =

 4     6     5  
 7     8     4     
 6     5     9    
 1     0     0     
 0     1     0     
 0     0     1     

B =

 1     0     0     0     0     0
 0     1     0     0     0     0
 0     0     1     0     0     0
 0     0     0    -1     0     0
 0     0     0     0    -1     0
 0     0     0     0     0    -1

Is there a way to tell Matlab to switch, for instance, column 1 in A with column 3 in B?

Upvotes: 3

Views: 2069

Answers (3)

gnovice
gnovice

Reputation: 125874

You can actually perform this column swap in one line and without the need for dummy variables using the function DEAL:

[A(:,1),B(:,3)] = deal(B(:,3),A(:,1));

Upvotes: 5

Amro
Amro

Reputation: 124563

tmp = A(:,1);
A(:,1) = B(:,3);
B(:,3) = tmp;

Upvotes: 5

Tristan
Tristan

Reputation: 916

Use

A(:,1) = B(:,3);

Or to actually swap them, you can use:

dummy = A(:,1);
A(:,1) = B(:,3);
B(:,3) = dummy;

Upvotes: 1

Related Questions