Create a table every n rows from another table

8 Ansichten (letzte 30 Tage)
H Carlos
H Carlos am 19 Aug. 2021
Kommentiert: H Carlos am 19 Aug. 2021
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!

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 19 Aug. 2021
%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 Kommentare
Walter Roberson
Walter Roberson am 19 Aug. 2021
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 am 19 Aug. 2021
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!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Tables finden Sie in Help Center und File Exchange

Produkte


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by