MATLAB Answers

Separating tables in tables after importing

1 view (last 30 days)
ArslanS
ArslanS on 14 Jun 2019
Answered: Peter Perkins on 19 Jun 2019
Hi,
I am importing a large delimiated table from a text file which has the following structure
x, x, x, x
x, x, x, x
x, x, x, x
null null null null
x, x, x, x
x, x, x, x
x, x, x, x
each sub table in this large table is basically sperated with an empty space. when I import these in Matlab, I basically get a continous table but I need the different subtables to be identified and placed into a seperate variable. how can I do this ?

  1 Comment

Guillaume
Guillaume on 14 Jun 2019
and placed into a seperate variable
Do not do that! Either store them together in a single container variable (a cell array) or actually keep it all together in the same table with an additional column indicating which subtable the row belongs to. The later will actually make your life easier if you want to calculate statistics across the subtables. Either way do not split the data across variables.
An example file and the code you're using to import that file would be useful.

Sign in to comment.

Answers (1)

Peter Perkins
Peter Perkins on 19 Jun 2019
Walter is correct, it's probaby not a good idea to split the table into separate workspace variables. And as he also says, it's maybe not even necessary to split the data up at all. It all depends on what you need to do with them. So the real question is, why do you want to do this? I'm genuinely asking, because tools like groupsummary or varfun let you do simple things like group means (and even some more complicated things) without splitting the data up.
If you are starting from a table like this ...
>> tt = table([1;2;3;NaN;4;5;6;7],[11;12;13;NaN;14;15;16;17])
tt =
8×2 table
Var1 Var2
____ ____
1 11
2 12
3 13
NaN NaN
4 14
5 15
6 16
7 17
... then what you want to do is to find the break points and then gather up the rows of each subtable. (tt.Group is also the thing that Walter alludes to: "an additional [variable] indicating which subtable the row belongs to".) The most straight-forward way is to use a loop:
>> tt.Group = 1 + cumsum(isnan(tt.Var1));
>> tt.Group(isnan(tt.Var1)) = NaN
tt =
8×3 table
Var1 Var2 Group
____ ____ _____
1 11 1
2 12 1
3 13 1
NaN NaN NaN
4 14 2
5 15 2
6 16 2
7 17 2
>> c = cell(max(tt.Group),1);
>> for i = 1:length(c)
c{i} = tt(tt.Group == i,1:2);
end
>> c{:}
ans =
3×2 table
Var1 Var2
____ ____
1 11
2 12
3 13
ans =
4×2 table
Var1 Var2
____ ____
4 14
5 15
6 16
7 17

  0 Comments

Sign in to comment.

Products


Release

R2019a

Translated by