Shuffling an array of cells (Matlab)

I'm currently trying to shuffle the contents of a 1 x N cell array in Matlab using the following code:

shuffledframes = frames{randperm(NumberOfFrames)}; frames=shuffledframes; %printing cell array contents for i=1:NumberOfFrames frames(i) end 

However, the contents of the frame do not seem sufficient ...

Is there an error in the code that I do not see?

+5
source share
1 answer

You need to replace

 shuffledframes = frames{randperm(NumberOfFrames)}; 

one of the following:

  • Standard recommended method:

     shuffledframes = frames(randperm(NumberOfFrames)); 
  • A more sophisticated alternative using lists:

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

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

In approach 1 above, frames(randperm(NumberOfFrames)) indexes the original array of cells with an index vector to create the new array of cells you want.

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

To see this more clearly, pay attention to the right 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] 
+7
source

Source: https://habr.com/ru/post/1203142/


All Articles