How can I write table variable units to a file?

16 views (last 30 days)
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

Answers (2)

Zoltan Danilo
Zoltan Danilo on 13 Oct 2017
Edited: Walter Roberson on 13 Oct 2017
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 Comment
Peter Krammer
Peter Krammer on 10 Nov 2022
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).

Sign in to comment.


Rodney
Rodney on 9 May 2019
If you save it as a .mat file it will retain all of the table properties (metadata) including units.
  1 Comment
Peter Krammer
Peter Krammer on 10 Nov 2022
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.

Sign in to comment.

Categories

Find more on Tables in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!