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

Viewed 222

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.

3 Answers

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.

Here's a vectorized way:

A = cat(3, [1 2 3; 4 5 6; 7 8 9], [10 11 12; 13 14 15; 16 17 18]); % define data
s = size(A); % get size of A
[~, ind] = sort(rand(s), 3); % indices of random permutations along 3rd dim
result = A(reshape(1:s(1)*s(2),s(1),s(2)) + (ind-1)*s(1)*s(2)); % linear index and result

the below script does a random shuffling in the 3rd dimension,

% creating a sample data, can be complex numbers
x=magic(10);
x=reshape(x,[4,5,5]);

% split 3D matrix into 2D cell arrays of vectors, permute those, and get back to 3D
y=num2cell(x,3);
newy=cellfun(@(x) x(randperm(length(x))), y,'uni',false);
newx=cell2mat(newy);

you can call permute followed by num2cell to partition your 3D array in different ways to shuffle it in a different dimension, for example,

x=permute(x,[2,3,1]);
y=num2cell(x,3);

the above code will create a 5x5 cell arrays of vectors of 4 elements (i.e. the 1st dimension), then you can use cellfun/cell2mat to do a random shuffling of the 1st dimension, then call permute again to change it back to the original dimension order.

Related