Search code examples
matlabrandompermutationcell-array

Random permutation of each cell in a cell array


I have a 1-by-4 cell array, D. Each of the cell elements contains 2-by-2 double matrices. I want to do random permutation over each matrix independently which in result I will have the same size cell array as D but its matrices' elements will be permuted and then the inverse in order to obtain the original D again.

for a single matrix case I have the code and it works well as follows:

A=rand(3,3)
p=randperm(numel(A));
A(:)=A(p)
[p1,ind]=sort(p);
A(:)=A(ind)

but it doesn't work for a cell array.


Solution

  • The simplest solution for you is to use a loop:

    nd = numel(D);
    D_permuted{1,nd} = [];
    D_ind{1,nd} = [];
    for d = 1:nd)
        A=D{d};
        p=randperm(numel(A));
        A(:)=A(p)
        [~,ind]=sort(p);
    
        D_permuted{d} = A;
        D_ind{d} = ind;
    end
    

    Assuming your D matrix is just a list of identically sized (e.g. 2-by-2) matrices, then you could avoid the loop by using a 3D double matrix instead of the cell-array.

    For example if you hade a D like this:

    n = 5;
    D = repmat([1,3;2,4],1,1,n)*10  %// Example data
    

    Then you can do the permutation like this

    m = 2*2;  %// Here m is the product of the dimensions of each matrix you want to shuffle
    [~,I] = sort(rand(m,n));  %// This is just a trick to get the equivalent of a vectorized form of randperm as unfortunately randperm only accepts scalars
    idx = reshape(I,2,2,n);
    D_shuffled = D(idx);