merge columns of cell array into matrix

2 views (last 30 days)
Florian
Florian on 17 Jul 2018
Answered: Guillaume on 17 Jul 2018
Given a cell array that contains various time tables. All time tables are of the same size.
X = rand(5,3);
Y = rand(5,3);
Time = seconds(1:5);
T1 = array2timetable(X,'RowTimes',Time)
T2 = array2timetable(Y,'RowTimes',Time)
A{1} = T1; A{2} = T2;
How can I convert certain columns of each cell into a single matrix/table? The result should look like B.
B = [A{1}.(2) A{2}.(2)]
A contains hundreds of time tables. Is there a more efficient way than addressing each column explicitly?

Answers (2)

James Clinton
James Clinton on 17 Jul 2018
Hi Florian,
If I'm understanding your request correctly, it looks like you want to avoid typing in each cell index of A individually. My first thought was to try to use the colon operator but I do not know of a way to accomplish your task using that method. Instead I have a longer method, but it will still automate the process of extracting a specified column of each cell in A.
[nrowsA ncolsA] = size(A); % find the number of cells, in this case ncolsA, in A
desiredCol = 2; % Specifying we want to get the data from column 2 in each cell
[outRows outCols] = size(A{1}); % need to know the size of the columns we will be extracting
B = zeros(outRows,ncolsA); % allocate memory for B now that we know size
for i = 1:ncolsA
B(:,i) = A{i}.(desiredCol); % extract desired column and store in B
end
Hope this helps!

Guillaume
Guillaume on 17 Jul 2018
Assuming all the tables have the same variable names, then you could convert the cell array of tables into a structure array:
s = cellfun(@(t) table2struct(timetable2table(t)), yourcellarray);
You can then easily concatenate the relevant field of the struct array:
[s.(fieldnames{2})] %for the 2nd column
However, I would recommend a completely different method of storing your tables. Instead of multiple tables, have just one table with an additional column, a categorical variable which indicates which table it originally came from. Then your concatenation is already done. And you can always identify which table the data originally came from with that categorical variable. It's also easy to perform calculation per original table using rowfun or varfun with the 'GoupingVariables' option, e.g. calculate the mean of column 2 per original table:
m = rowfun(@mean, bigtable, 'InputVariables', 2, 'GroupingVariables', 'identifiercolumn');

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!