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 ?
shuffledframes = frames(randperm(NumberOfFrames));
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);
a(randperm(size(a, 1)), :) shuffle the elements of each column in the matrix.
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.
You need to replace
shuffledframes = frames{randperm(NumberOfFrames)};
by either of these:
Standard, recommended way:
shuffledframes = frames(randperm(NumberOfFrames));
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With