6

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.

Ander Biguri
  • 35,140
  • 11
  • 74
  • 120
Zander
  • 167
  • 1
  • 10
  • You may find a slight connection between this question and [**the previous one of mine**](https://stackoverflow.com/questions/45665684/finding-number-of-all-nested-cells-in-a-complex-cell) – Zander Aug 17 '17 at 02:12
  • 1
    What would be some examples of a random location? – rayryeng Aug 17 '17 at 04:59
  • 1
    Do you mean that each `1` should have an equal chance of selection, as per the sample array shown? – crazyGamer Aug 17 '17 at 05:01
  • @rayryeng The example could be `CellArray{1}` or `CellArray{4}{4}{1}` or any other member's location in the nested cell – Zander Aug 17 '17 at 05:30

1 Answers1

9

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))}
rahnema1
  • 15,264
  • 3
  • 15
  • 27
  • 4
    You can get the same result from `regexp` with `m = regexp(s, '\{[^\=]*\}', 'match');`, which I would argue is a clearer representation of what the user is getting out of the regex. Still, very clever, +1 – sco1 Aug 17 '17 at 11:54
  • @rahnema1,@excaza _Thank you for sharing your valuable knowledge._ – Zander Aug 17 '17 at 14:31
  • 1
    @Amin Glad if it can help! – rahnema1 Aug 17 '17 at 14:32
  • @rahnema1 **Just as a minor additional question, if I want to change the value of the location which is chosen in the `CellArray`, how can I do that?** – Zander Aug 17 '17 at 14:34
  • 1
    @Amin `eval` may help. `idx = 5;value = 3;eval(['CellArray' m{idx} '=' num2str(value) ';'])` – rahnema1 Aug 17 '17 at 14:49
  • @rahnema1 Thanks a million! – Zander Aug 17 '17 at 15:09