3

Consider the following cell array:

A={1:3,[20,40],100}

A =

1×3 cell array

   {1×3 double}    {1×2 double}    {[100]}

I'd like a way to retrive the linear index of the values stored it, for example if I flatten the array using:

[A{:}]

ans =

     1     2     3    20    40   100

I can see that the 4th linear index is 20 etc. So is there a way similar the matrix linear index that will give me for a cell array A((4)) the value 20 in the example? (I of course just invented the (()) notation for illustration purposes.

bla
  • 25,846
  • 10
  • 70
  • 101
  • I think it will be a good idea to modify the `subsref` function for this example. I like the new operator too `((.))`. – Autonomous Mar 14 '18 at 22:36
  • See https://stackoverflow.com/questions/3627107/how-can-i-index-a-matlab-array-returned-by-a-function-without-first-assigning-it – Nicky Mattsson Mar 15 '18 at 10:30

2 Answers2

5

There isn't a straightforward solution, as far as I know. Here's a way to achieve that. It works even if the inner arrays are not row vectors; in that case they are implicitly considered to be linearized.

A = {1:3,[20,40],100}; % data
ind = 4; % linear index into flattened data
s = [0 cumsum(cellfun(@numel, A))];
ind_outer = find(ind<=s, 1) - 1;
ind_inner = ind - s(ind_outer);
result = A{ind_outer}(ind_inner);
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
0

If you don't want to convert your cell array of matrices into a straight numerical matrix, it's hard to determine the linear index to a specific element of a specific matrix since you don't know the "full size" if your data.

You can retrieve elements of matrices within your cell arrays:

value = A{1,2}(1,1) % 20

That gets the the underlying value of the second cell in the first row of cells ({1,2}) and retrieve the element in the first row and column ((1,1)). If you want, you can rewrite the command so that it takes into account only a single dimension:

value = A{2}(1) % 20
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98