Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a cell array (Matlab)

Tags:

shuffle

matlab

I am currently trying to shuffle the content of a 1 x N cell array in matlab using the follwoing code:

shuffledframes = frames{randperm(NumberOfFrames)};
frames=shuffledframes;

%printing cell array contents
for i=1:NumberOfFrames
    frames(i)
end

However the frame contents do not seem to suffle...

Is there a bug in the code, that i do not see ?

like image 586
asterix Avatar asked Sep 22 '14 13:09

asterix


People also ask

How do you shuffle cells in Matlab?

shuffledframes = frames(randperm(NumberOfFrames));

How do you randomize an array in Matlab?

You can use the randperm function to create a double array of random integer values that have no repeated values. For example, r4 = randperm(15,5);

How do you shuffle data in a matrix in Matlab?

a(randperm(size(a, 1)), :) shuffle the elements of each column in the matrix.

How do you shuffle a row in Matlab?

shuffledArray = orderedArray(randperm(size(orderedArray,1)),:); randperm will generate a list of N random values and sort them, returning the second output of sort as result.


1 Answers

You need to replace

shuffledframes = frames{randperm(NumberOfFrames)};

by either of these:

  1. Standard, recommended way:

    shuffledframes = frames(randperm(NumberOfFrames));
    
  2. More complicated alternative using lists:

    [frames{:}] = frames{randperm(NumberOfFrames)};
    

Why? In your original code, frames{randperm(NumberOfFrames)} gives a comma-separated list of numbers. Matlab only takes the first number of that list and assigns it to shuffledframes.

In approach 1 above, frames(randperm(NumberOfFrames)) indexes the original cell array with an index vector to produce a new cell array, which is what you want.

Approach 2 has the same desired effect, although it is unnecessarily more complicated. It works by matching one list with another list. Namely, Matlab respectively fills each value of the list frames{:} with each value of the list frames{randperm(NumberOfFrames)}.

To see this more clearly, observe the right-hand side of the first line of your code, and compare with approach 1:

>> frames = {1,2,3,4};
>> NumberOfFrames = 4;
>> frames{randperm(NumberOfFrames)} %// Your code. Gives a list of values.
ans =
     3
ans =
     4
ans =
     2
ans =
     1

>> frames(randperm(NumberOfFrames)) %// Approach 1. Gives cell array.
ans = 
    [3]    [1]    [4]    [2]
like image 90
Luis Mendo Avatar answered Sep 23 '22 16:09

Luis Mendo