File Exchange

## RANDSWAP

version 1.0 (2.32 KB) by

randomly swap elements of a matrix

Updated

For vectors, Y = RANDSWAP(X) randomly swaps the elements of X. For N-D matrices, RANDSWAP(X) randomly swaps the elements along the first non-singleton dimension of X.

RANDSWAP(X,DIM) randomly swaps the elements along the dimension DIM. For instance, RANDSWAP(X,1) randomly interchanges the rows of X.

Y = RANDSWAP(X,'partial') swaps the elements for each of the non-singleton dimensions of X separately. Rows are interchanged first, then columns, then planes, etc. In this case, elements that belong to the same row, column, ... stay together.

Y = RANDSWAP(X,'full') randomly swaps all the elements in X.

[Y, I, J] = RANDSWAP(...) return index matrices I and J so that Y = X(I) and X = Y(J).

X can be a numeric or a cell array.

Version 2.0 (nov 2007)

Sugato

h612

### h612 (view profile)

Is there a way to store the new index of the new matrix? Im using for training and testing- and I'd like to arrange labels according to the new arrangement.

RAVI KUMAR

Thank you

Pernille

Thanks

Fiqqih Faizah

it's great
thank you

Florian

ALiveris

### ALiveris (view profile)

thanks a lot, worked good with my cell array

Jos (10584)

### Jos (10584) (view profile)

@Andrey ... or use randperm directly, of course

ri = randperm(size(a,1))
ra = a(ri,ri)

Jos (10584)

### Jos (10584) (view profile)

@Andrey, you could accomplish this using the 2nd output of randswap:

a = reshape(1:25,5,5)
[ra,i] = randswap(a,1) % swap rows
ra = ra.' ; % transpose (columns become rows)
ra = ra(i) ; % swap rows again
ra = ra.' ; transpose again

Andrey Sokolov

### Andrey Sokolov (view profile)

For QAP, I need to scramble rows and columns of the adjacency matrix in exactly the same way. It would be nice if there was an option to apply the same permutation to both dimensions for scrambling square matrices.

grega

### grega (view profile)

Thank you for this great function!

Would it be possible to update the function with an argument specifying distribution also?

I suppose randomization is done according to uniform distribution. It would be great if it works also with other, e.g. normal, binomial, poisson, inverse of normal etc.

Thank you!

Kevin Grey

### Kevin Grey (view profile)

Great! This is exactly what I wanted. For network analysis of Quadratic Assignment Procedure (QAP), this step is pre-required.

Jos (the author)

Thanks Yidong for pointing out the errors. I am very sorry and will update the file shortly. Jos

Yidong Li

Unfortunately, it doesn't work for me. First thing confused me:
the line 68, all the "dim" should be "dimmode", is that right?
Second thing: Even I modified them, I still couldn't get the correct answer to "randswap(X,1)". The result seems like "randswap(X)".
Can you other guys check it as well?

MATLAB 6.5 (R13)