Search code examples
arraysstringmatlabcellpermutation

Rearranging a cell array


I'm programming a task for a research study. The problem I have is the following: I have a dictionary with names and with one picture per cell. Like that:

nameCues1 = {'Lisa','Anna', 'Sarah', 'Nina', 'resized_1.jpg' };
nameCues2 = {'Emma', 'Lena', 'Gabi', 'Steffi', 'resized_2.jpg' };

I have loaded them into a cell array, created a random sequence:

nameCuesAll = {nameCues1,nameCues2};

randSeq3 = nameCuesAll(randperm(size(nameCuesAll,2)));

Then I loop over it to read in the names of the dictionary and the corresponding picture:

for i = 1:numel(nameCuesAll)
    pics3{i} = imread(randSeq3{i}{1,5});
    ind{i}=randSeq3{i}(randperm(numel(randSeq3{i})));
end

Then I prompt it on the screen via Psychtoolbox, a toolbox specialized in creating tasks for research, for those who don't know:

for j = 1:4
    % (left out unnecessary other functions)
    DrawFormattedText(window,ind{i}(j), 'center', 'center', white, [], [], [], [], [], rect);
end

The problem is that the names of the dictionary are not shown in randomized order, and every try I had until now has thrown errors. The main problem is that I don't know how to correctly randomize/index the dictionary-names.

Thanks for any ideas!


Solution

  • To reorder the elements of a cell array, you should reference elements using ():

    nameCues1 = {'Lisa','Anna', 'Sarah', 'Nina', 'resized_1.jpg' };
    rIdx = randperm(numel(nameCues1));
    mixedCues = nameCues1(rIdx)
    

    which yields for the case of rIdx = [3 5 1 4 2]:

    mixedCues =
    
      1×5 cell array
    
        {'Sarah'}    {'resized_1.jpg'}    {'Lisa'}    {'Nina'}    {'Anna'}
    

    Then use mixedCues instead of nameCues1.

    See also: Access Data in Cell Array.