How can I write table variable units to a file?

25 次查看(过去 30 天)
Hi!
I'm working with some tables and I've assigned values to the VariableUnits Property field of the table (I also have variable names). I'd like to use writetable to write the table to a file and I'd like to have the VariableNames be the first row and their units appear below, is there any way to do this? I've set the 'WriteVariableNames' part to true and that works, but getting the units in there seems a bit more difficult.
Thanks, David

回答(2 个)

Zoltan Danilo
Zoltan Danilo 2017-10-13
编辑:Walter Roberson 2017-10-13
Hi,
Not an ultimate solution, just a quick fix of the problem.
function [] = WriteTableWithUnits( TableToWtrite, FileName )
%WriteTableWithUnits
% To write tables with names and units of columns and row names
[RowNum, ColNum]=size(TableToWtrite);
HeaderRow=cell(1,ColNum+1);
HeaderRow{1,1}='Rows';
TableToSave=cell2table(cell(RowNum+1, ColNum+1));
for iCol=1:ColNum
HeaderRow{1,iCol+1}=[TableToWtrite.Properties.VariableNames{iCol}, ' [', TableToWtrite.Properties.VariableUnits{iCol},']'];
end
TableToSave{1,:}=HeaderRow;
TableToSave{2:end,1}=TableToWtrite.Properties.RowNames(:);
TableToSave{2:end,2:end}=table2cell(TableToWtrite(:,:));
writetable(TableToSave, FileName, 'WriteVariableNames', false);
end
  1 个评论
Peter Krammer
Peter Krammer 2022-11-10
Thanx Zoltan for your Idea, but it does not works correctly. Your code gives me error in line 12
(To assign to or create a variable in a table, the number of rows must match the height of the table.)
I have a similar problem - to write Table into csv or xls file with Units and Descriptions.
In function writetable, I did not see an option for writing a Units / Descriptions into csv / xls.
And if I write it non-standart, then I have a problem with reading back (with readtable() function ).
Currently, I see the only solution - save to mat file using a save(...) function , but it is not portable/presentable for non-matlab users (they cant read mat file).

请先登录,再进行评论。


Rodney
Rodney 2019-5-9
If you save it as a .mat file it will retain all of the table properties (metadata) including units.
  1 个评论
Peter Krammer
Peter Krammer 2022-11-10
Sure, but mat files are not the best cross-platform files, for easy reading and presenting for non-matlab users.
Csv or xls file representation could be open by many programs; also csv could be reading directly by every text editor. So it looks much more suitable for presenting and cross-platform uses.

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by