How do I display two separate tables with 2 column headings the same side-by-side?
34 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sarah Hughes
el 15 de Dic. de 2019
Comentada: Sarah Hughes
el 15 de Dic. de 2019
I need to display two separate tables side by side with different row lengths and both tables have the same column headings.
Please see the expected table for how the data should look like.
Thank you in advance
1 comentario
dpb
el 15 de Dic. de 2019
You'll have to write the data as you want explicitly; a MATLAB table can't contain columns with duplicate variable names nor empty rows. The latter you could handle by just empty data; the first is inviolate rule.
It depends upon what you really mean by "display" as to what your choices are...
Respuesta aceptada
Adam Danz
el 15 de Dic. de 2019
Editada: Adam Danz
el 15 de Dic. de 2019
First you need to pad the shorter table so it matches the same number of rows as the longer table. The two decisions you need to make are 1) what value should be used as a pad and 2) where should the padded rows be added - to the end, beginning, at certain rows, etc. This demo pads table 2 with NaN values at the end of the table.
% Create demo data, T2 has less rows than T1; both have same headers.
T1 = table({'A';'B';'C';'D';'E'},rand(5,1),rand(5,1),'VariableNames',{'HighFiberDiet','Aerobic','Anaerobic'});
T2 = table({'A';'B';'C';'D'},rand(4,1),rand(4,1),'VariableNames',{'HighFiberDiet','Aerobic','Anaerobic'});
% Pad T2 to match the number of rows in T1; this creates a table of
% NaN values and adds them to T2.
T2Pad = [T2;array2table(nan(size(T1,1)-size(T2,1),size(T2,2)),'VariableNames',T2.Properties.VariableNames)];
Now T2Pad and T1 have the same number of rows.
To concatenate both tables with the same headers side-by-side, you can use mergevars() (requires Matlab release >=r2018a) along with the MergeAsTable option to create two sub-tables. I named the two super-tables Table_1 and Table_2.
T3 = [mergevars(T1,T1.Properties.VariableNames,'NewVariableName','Table_1','MergeAsTable',true),...
mergevars(T2Pad,T2Pad.Properties.VariableNames,'NewVariableName','Table_2','MergeAsTable',true)];
The result:
T3 =
5×2 table
Table_1 Table_2
HighFiberDiet Aerobic Anaerobic HighFiberDiet Aerobic Anaerobic
______________________________________ _____________________________________
{'A'} 0.081273 0.11895 {'A' } 0.70981 0.086412
{'B'} 0.84107 0.86276 {'B' } 0.50521 0.21126
{'C'} 0.7004 0.94128 {'C' } 0.27705 0.30743
{'D'} 0.61522 0.70038 {'D' } 0.88835 0.64141
{'E'} 0.013579 0.39019 {[NaN]} NaN NaN
Más respuestas (0)
Ver también
Categorías
Más información sobre Data Type Identification en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!