Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linear indexing for cell array elements in matlab

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.

like image 808
bla Avatar asked Dec 14 '25 18:12

bla


1 Answers

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);
like image 180
Luis Mendo Avatar answered Dec 16 '25 22:12

Luis Mendo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!