File Exchange

image thumbnail


version 5.0 (2.16 KB) by Jos (10584)
Randomize a matrix along one dimension


Updated 07 Feb 2019

View Version History

View License

shake - Randomize a matrix along a specific dimension
Y = shake(X) randomizes the order of the elements in each column of the
2D matrix. For N-D matrices it randomizes along the first non-singleton

shake(X, DIM) randomizes along the dimension DIM.

[Y, I, J] = shake(X) returns indices so that Y = X(I) and X = Y(J).

A = [1 2 3 ; 4 5 6 ; 7 8 9 ; 10 11 12] ; % see <SLM> on the FEX ...
B = shake(A, 2) % -> each row is shaked randomly
% 3 2 1
% 6 4 5
% 7 8 9
% 11 10 12%
C = sort(B, 2) % -> equals A!

For vectors V, shake(V) is similar to V(randperm(numel(V)).

The function of shake can be thought of as holding a matrix and shake
in a particular direction (dimension), so that elements are getting
shuffled within that direction only.

Cite As

Jos (10584) (2021). shake (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (8)

Kevin Bolding

I found I needed to change line 68 when going to higher dimensions. Not thoroughly tested but this may work:
I = shiftdim(reshape(I,sz),dim-ndim);




Thanks, this is just what I needed. However I'm finding it to be quite slow. I have ~10000 rows and 5 columns, and I am randomising by column (Dim = 1). Do you have any suggestions as to how to speed this up? Is doing each column vector separately faster?

Jos (author)

New version: 3.0 (oct 2006)

Gregory Anderson

Simple? Yes, but I couldn't figure out how to do it on my own, and it does exactly what it's supposed to do, so thanks, Jos.

Jos vdG

Which tests? Note that <shake> simply uses the built-in matlab <rand> function ...

Peter He

Tests show that the quality of randomization is not good. Cannot be trusted in serious simulations.

John D'Errico

Its not shaky at all. Certainly not its documentation, which is as clear as even I could ask for.

MATLAB Release Compatibility
Created with R2018b
Compatible with any release
Platform Compatibility
Windows macOS Linux

Inspired: randone1, RANDSWAP, Permute a grouped vector

Community Treasure Hunt

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

Start Hunting!