问题
Suppose you have the following data:
A = [1,2,3;4,5,6];
headers = {'force', 'mass', 'acceleration'};
units = {'N','Kg','m/s^2'};
Let's say I want to convert it to a table, where headers
will be the 'VariableNames'
:
table_of_data = cell2table([units; num2cell(A)]);
table_of_data.Properties.VariableNames = headers
table_of_data =
force mass acceleration
_____ ____ ____________
N 'Kg' 'm/s^2'
[2] [3]
[5] [6]
Note that the first two columns of A
are removed. This is because MATLAB treats the single character N
differently than 'Kg'
and 'm/s^2'
. If I insert a space after 'N '
I get:
table_of_data =
force mass acceleration
_____ ____ ____________
'N ' 'Kg' 'm/s^2'
[1] [2] [3]
[4] [5] [6]
How can I get a proper table, with all elements displayed without inserting a space 'N '
?
It's no problem to use a single character in units
if I add more rows to the cell array, such as [headers; units; num2cell(A)]
, so the following works:
table_of_data = cell2table([headers; units; num2cell(A)]);
table_of_data(1,:) = [];
table_of_data.Properties.VariableNames = headers
table_of_data =
force mass acceleration
_____ ____ ____________
'N ' 'Kg' 'm/s^2'
[1] [2] [3]
[4] [5] [6]
How can I solve this without turning to cumbersome workarounds?
回答1:
This likely has to do with table
's internal representation of the data. It seems like what it does is tries to vertically concatenate the data in a column and if the concatenation succeeds then it uses an array, otherwise it stores it as a cell
.
In the case of a single character N
and the numbers, 1
and 4
, they can be concatenated without error; however, it converts them all to chars.
vertcat('N', 1, 4)
However, when you add the space, concatenation now fails
vertcat('N ', 1, 4)
And the output is displayed like a cell.
You have a few options:
Use
table.Properties.VariableUnits
to store the units rather than trying to incorporate the units into your table.table_of_data.Properties.VariableUnits = units;
Display the units in the column headers
headers = {'force_N', 'mass_kg', 'acceleration_m_s2'};
Create a double-nested cell array to store all of the units, which explicitly causes it to be stored as a cell array internally.
table_of_data = cell2table([num2cell(units); num2cell(A)])
来源:https://stackoverflow.com/questions/39298858/cell2table-removes-values-from-first-column-if-string-is-a-single-character