Create a table every n rows from another table

8 次查看(过去 30 天)
I have a big data table of 960x2. It's a sequence of 8 experimental trials, and I am trying to separate the data for each trial into individual tables. Each trial lasts 120 rows.
I wish to create a table for every 120 rows and all columns of the original table. As a result, I want to have 8 tables that are 120x2.
I don't mind transforming the tables into matrices if it's required.
I would also like to name these tables as Table1, Table2, Table3, ... Table 8. Is there a way to do it all at once, like in a for loop or something?
Thank you!

采纳的回答

Walter Roberson
Walter Roberson 2021-8-19
%some data for illustration
YourTable = table(randi(9, 960, 1), randi([10 19], 960, 1));
%do the work
temp = num2cell(permute(reshape(YourTable{:,:}, 120, 8, 2), [1 3 2]), [1 2]);
Tables = cell2struct(temp(:), ("Table" + (1:length(temp)).') )
Tables = struct with fields:
Table1: [120×2 double] Table2: [120×2 double] Table3: [120×2 double] Table4: [120×2 double] Table5: [120×2 double] Table6: [120×2 double] Table7: [120×2 double] Table8: [120×2 double]
You might have noticed that I did not create variable names Table1 and so on. See http://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
  4 个评论
Walter Roberson
Walter Roberson 2021-8-19
In the case where the number of output tables is fixed in advanced:
%some data for illustration
YourTable = table(randi(9, 960, 1), randi([10 19], 960, 1));
%do the work
temp = num2cell(permute(reshape(YourTable{:,:}, 120, 8, 2), [1 3 2]), [1 2]);
temp = cellfun(@(DATA) array2table(DATA, 'variablenames', YourTable.Properties.VariableNames), temp(:), 'uniform', 0);
[Table1, Table2, Table3, Table4, Table5, Table6, Table7, Table8] = deal(temp{:});
whos
Name Size Bytes Class Attributes Table1 120x2 3119 table Table2 120x2 3119 table Table3 120x2 3119 table Table4 120x2 3119 table Table5 120x2 3119 table Table6 120x2 3119 table Table7 120x2 3119 table Table8 120x2 3119 table YourTable 960x2 16559 table temp 8x1 25784 cell
In the case where the number of output tables is not fixed in advance, such as the case where you want to split the table into "however many is needed" sub-tables 120 rows at a time, then the best way to do that is: DONT'.
Re-read the link I posted earlier about reasons why you should not dynamically create variable names.
H Carlos
H Carlos 2021-8-19
I see. I'll re-read the link to make sure I understand. Other than that, it does what I want. Thank you so much for all the help!

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Tables 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by