Search code examples
data-structuresoctavecell-array

Access Values of Cell Array deeply nested within Structure Array


I have a nested structure_array/cell_array/structure_array of character values which is the result of a web query which returns a converted JSON object, the needed numeric value(s) of which I can access in loops thus:

for ix = 1 : size( S.orderBook.buckets , 2 )
 if ( str2double( S.orderBook.buckets{ ix }.price ) >= str2double( S.orderBook.price ) )
  mid_ix = ix ;  
  break ;
 endif
endfor

The above loop gets the index, mid_ix, of the cell in the middle of the region of interest, and

orderbook_begin_ix = mid_ix - 20 ; orderbook_end_ix = mid_ix + 20 ;

jj = 0 ;
for ix = orderbook_begin_ix : orderbook_end_ix
 jj = jj + 1 ;
 new_orderbook_data( 1 , jj ) = str2double( S.orderBook.buckets{ ix }.longCountPercent ) ;
endfor

this second loop fills the pre-initialised matrix, new_orderbook_data, with the values of interest.

However, I was wondering whether there is a quicker/more elegant way of getting these values? At the moment, as can be seen above, I am having to run a "look up" for loop that encloses an "if statement" to get in the ballpark of the required numeric values, and then run a second for loop in the region of the ballpark to extract these required values.

Note: cross posted at Octave forum


Solution

  • I think I have solved this by using the syntax below:

    prices = cellfun( @str2double , { [ S.orderBook.buckets{:} ].price } ) ;
    

    which gives me a matrix "prices" to which I can further apply vectorised code.

    Explanation:-

    1. the { : } extracts the prices from the cell array into a comma separated list,
    2. the enclosing [ ] puts this list into a structure array,

    3. the [ ].price extracts just the prices which are then put back into a cell array with the outermost enclosing { }

    4. and then the string values are converted to numeric by applying the cellfun to this prices cell array and

    5. are finally assigned to the "prices" matrix.