Search code examples
arraysmatlabcell

Matlab, Random Cell Array


I have a cell array Q, wich contains questions. And a Logical vector containing 1/0 as true / false and in same order as Q like this:

Q = {'A ball is squared: ' 'My computer is slow: ' 'A triangle has 3 corners: '};
A = {0 1 1};

I would then make a Q_random, containing the questions from Q but in randomly order and a A_random contaning the logical numbers which respond to the Q_random. I've come up with this code, but i not sure that this is the best way to do it.

Could I use another method, which is more simple and effective ?

Q = {'A ball is squared: ' 'My computer is slow: ' 'A triangle has 3 corners: '};
A = {0 1 1};
Q_random = cell(1,numel(Q));
A_random = cell(1,numel(Q));

i = 1;
while (i <= numel(Q));
random_number = randi(numel(Q));
if isempty(Q_random{random_number});
    Q_random(random_number) = Q(i);
    A_random(random_number) = A(i);
    i = i + 1;
else
end    

Solution

  • I would use randperm to generate randomly ordered indexes

    rand_ind=randperm(length(Q));
    

    and then use the random indexes to generate the randomly permuted cell arrays

    Q_random=Q(rand_ind);
    A_random=A(rand_ind);
    

    This answer to a previous related question may also be worth looking at.