MATLAB: Convert nested struct to matrix

convertmatrixstruct

Hi
I have the following struct and would like to convert Stocks_10.Close into a matrix for vectorization
The following worked for equal fields.
stocks_10_cell = [stocks_10.Close]';
The issue is the data in Number 8, insted 757×1, it's 668×1.
I got the error:
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Does someone have a solution?
Thank you
Carsten

Best Answer

Well, you obviously can't concatenate vectors of dfferent sizes so if you want to do that you either have to trim the longer vectors or pad the shorter ones. Both of which are doable, but may mess up whatever calculation you want to do.
Instead, Perhaps the best approach would be to flatten all your data into a single table or timetable. You can then use groupsummary or similar functions to perform statistics according to groupings of your choosing:
%conversion of the structure to table:
%first replicate tickers so they're the same height as the other fields
%also convert Date to datetime as it will make life much easier
for si = 1:numel(Stocks_10)
Stocks_10(si).Ticker = repmat(Stocks_10(si).Ticker, size(Stocks_10(si).Open));
Stocks_10(si).Date = datetime(Stocks_10(si).Date); %may need extra options to perform the conversion properly
end
%then concatenate the whole lot and convert to table:
varnames = fiednames(Stocks_10);
stock_cell = cell(1, numel(varnames));
for fi = 1:numel(varnames)
stock_cell{fi} = vertcat(Stocks.(varnames(fi)));
end
stock_table = table(stock_cell{:}, 'VariableNames', varnames);
From them one, it's easy to do some stats, e.g. monthly mean of the variables per ticker:
ticker_monthlymean = groupsummary(stock_table, {'Date', 'Ticker'}, {'month', 'none'}, 'mean');
Or monthly mean regardless of ticker:
monthly_mean = groupsummary(stock_table, 'Date', 'month', 'mean', 2:width(stock_table)-1);