Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping rows and columns

Tags:

arrays

matlab

I need a MATLAB function that will swap 2 rows or 2 Columns with each other in a matrix of arbitrary size.

like image 771
Frank Avatar asked Feb 08 '11 23:02

Frank


2 Answers

Say you take the matrix

>> A = magic(4)
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

If you want to swap, say, columns 3 and 1, you write

>>A(:,[1 3]) = A(:,[3 1])

A =
     3     2    16    13
    10    11     5     8
     6     7     9    12
    15    14     4     1

The same works for swapping rows (i.e. A([4 2],:) = A([2 4],:) to swap rows 2 and 4).

like image 155
Jonas Avatar answered Sep 21 '22 22:09

Jonas


This function only works for 2 dimensional arrays:

function matrix = swap(matrix,dimension,idx_a,idx_b)

if dimension == 1
    row_a = matrix(idx_a,:);
    matrix(idx_a,:) = matrix(idx_b,:);
    matrix(idx_b,:) = row_a;
elseif dimension == 2
    col_a = matrix(:,idx_a);
    matrix(:,idx_a) = matrix(:,idx_b);
    matrix(:,idx_b) = col_a;
end

Example Call:

>> A = rand(6,4)

A =

0.8350    0.5118    0.9521    0.9971
0.1451    0.3924    0.7474    0.3411
0.7925    0.8676    0.7001    0.0926
0.4749    0.4040    0.1845    0.5406
0.1285    0.0483    0.5188    0.2462
0.2990    0.6438    0.1442    0.2940

>> swap(A,2,1,3)

ans =

0.9521    0.5118    0.8350    0.9971
0.7474    0.3924    0.1451    0.3411
0.7001    0.8676    0.7925    0.0926
0.1845    0.4040    0.4749    0.5406
0.5188    0.0483    0.1285    0.2462
0.1442    0.6438    0.2990    0.2940

>> tic;A = swap(rand(1000),1,132,234);toc;
Elapsed time is 0.027228 seconds.
>> 
like image 23
Miebster Avatar answered Sep 20 '22 22:09

Miebster