Search code examples
matlabmultidimensional-arrayrandomcell-array

Random selection of a member's location in a nested cell of cells: Matlab


I have a nested cell of cells like the one below:

CellArray={1,1,1,{1,1,1,{1,1,{1,{1 1 1 1 1 1 1 1}, 1,1},1,1},1,1,1},1,1,1,{1,1,1,1}};

I need to randomly pick a location in CellArray. All members' locations of CellArray must have same chances to be chosen in the random selection process. Thanks.


Solution

  • You can capture the output of the celldisp function. Then use regex to extrcat indices:

    s=evalc('celldisp(CellArray,'''')');
    m = regexp(s, '\{[^\=]*\}', 'match');
    
    • Thanks to @excaza that suggested a clearer use of regexp

    Result:

    m =
    {
      [1,1] = {1}
      [1,2] = {2}
      [1,3] = {3}
      [1,4] = {4}{1}
      [1,5] = {4}{2}
      [1,6] = {4}{3}
      [1,7] = {4}{4}{1}
      [1,8] = {4}{4}{2}
      [1,9] = {4}{4}{3}{1}
      [1,10] = {4}{4}{3}{2}{1}
      [1,11] = {4}{4}{3}{2}{2}
      [1,12] = {4}{4}{3}{2}{3}
      [1,13] = {4}{4}{3}{2}{4}
      [1,14] = {4}{4}{3}{2}{5}
      [1,15] = {4}{4}{3}{2}{6}
      [1,16] = {4}{4}{3}{2}{7}
      [1,17] = {4}{4}{3}{2}{8}
      [1,18] = {4}{4}{3}{3}
      [1,19] = {4}{4}{3}{4}
      [1,20] = {4}{4}{4}
      [1,21] = {4}{4}{5}
      [1,22] = {4}{5}
      [1,23] = {4}{6}
      [1,24] = {4}{7}
      [1,25] = {5}
      [1,26] = {6}
      [1,27] = {7}
      [1,28] = {8}{1}
      [1,29] = {8}{2}
      [1,30] = {8}{3}
      [1,31] = {8}{4}
    }
    

    Use randi to select an index:

    m{randi(numel(m))}