Search code examples
arraysmatlabrandomcomplex-numbers

How to shuffle within a specific dimension in a multidimensional array of complex numbers


I want to shuffle a 3-dimensional array with complex values, in such a way that elements are randomly rearranged along the 3rd dimension only.

For example, the 3D array of integers A (I remind that I'm looking for the same solution but for complex numbers array):

A(:,:1)= 1 2 3 ; 4 5 6 ; 7 8 9
A(:,:2)= 10 11 12; 13 14 15 ; 16 17 18

After shuffling the third dimension, a possible output could be:

A(:,:1)= 10 2 3 ; 4 14 6 ; 7 17 18
A(:,:2)= 1 11 12; 13 5 15 ; 16 8 9

How can I do this?

The only solution I've found includes compiled c function which doesn't work with a complex-valued array.


Solution

  • You can very simply iterate over the first two dimensions, and permute the elements along the third one:

    a = randn(3,5,2) + 1i*randn(3,5,2); % some complex data
    
    for jj=1:size(a,2)
      for ii=1:size(a,1)
        a(ii,jj,:) = a(ii,jj,randperm(size(a,3)));
      end
    end
    

    Note that this solution is likely faster than the cellfun solution in the other answer for very large arrays, as that solution requires large intermediate data to be stored and used.