tags:

views:

41

answers:

3

Hi everyone, 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?

+1  A: 

Use

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

Or to actually swap them, you can use:

dummy = A(:,1);
A(:,1) = B(:,3);
B(:,3) = dummy;
Tristan
Thanks for your reply, but this only takes what was in matrix B and puts it in A. Is there something that will take the column from B to A, and from A to B?
ajj
edited my response.
Tristan
+3  A: 
tmp = A(:,1);
A(:,1) = B(:,3);
B(:,3) = tmp;
Amro
+2  A: 

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));
gnovice
+1 good one, although it seems like an overkill for such a simple task
Amro
@Amro: Perhaps, but DEAL is a useful function to know about in general, so I figured I might as well list it as another possible solution. ;)
gnovice

related questions