Search code examples
matlabcell-arraydata-extraction

Extract (price data as) 1D vector from nested cell


Given:

data = { ...
    { '2014-12-31'    [79.2100] }  ...
    { '2014-12-30'    [79.3000] }  ...
    { '2014-12-26'    [79.1200] }  };

I need to extract:

prices = [ 79.2100, 79.3000, 79.1200 ];

What is a good way to accomplish this? A for loop would be simple to implement, and combined with pre-allocation would be reasonably efficient. But it looks a bit clumsy.


Solution

  • You could first convert your cell array to not a nested array and then extract the second column and convert from a cell to an array to a normal array using cat combined with {} indexing.

    % Turn your nested cell array into an N x 2 cell array
    data = cat(1, data{:});
    
    % Get just the second column
    prices = cat(2, data{:,2});