Table VariableNames Property Won't Print Directly

3 views (last 30 days)
Alan on 22 Sep 2014
Commented: Alan on 22 Sep 2014
I need to take an existing table I have, HTable and write all but the first column to a file, including the VariableNames (Column Headers) as the first line of the file.
Note: MLID is a file handle from an earlier fopen command.
The following code generates an error:
fstr = [repmat('%s,',1,length(HTable.Properties.VariableNames)-2),'%s\n'];
Error using fprintf
Function is not defined for 'cell' inputs.
OK, I need to dereference. But, the following code ONLY prints the second VariableName to the file:
fstr = [repmat('%s,',1,length(HTable.Properties.VariableNames)-2),'%s\n'];
But the following code works:
fstr = [repmat('%s,',1,length(HTable.Properties.VariableNames)-2),'%s\n'];
hdrs = HTable.Properties.VariableNames(2:end);
I guess I've found the workaround, but a deeper question for me is why? Why doesn't the second set of code produce the exact same thing as the third? Why should assigning one to a new variable before calling fprintf matter? Or is there some other method of dereferencing I would need to get all the values from the cell array?

Accepted Answer

Guillaume on 22 Sep 2014
Edited: Guillaume on 22 Sep 2014
The reason HTable.Properties.VariablesNames{2:end} does not work is because mathworks have overloaded and provided their own implementation of the '.', '{}', '()' operators (subsref) for tables.
If you want to know the nitty gritty, the reason it does not work is that, in toolbox\matlab\datatypes\@table\private\getProperty.m, when it comes to return the variable names, matlab does:
[varargout{:}] = variablenames{2:end}; %where variablenames is a cell array of the variable names
The {2:end} expands the cell array into a comma separated list (individual return values), and as you've only requested one output, only return the first one.
Note that the following would actually work:
c = cell(1, numel(HTable.Properties.VariableNames)-1);
[c{:}] = HTable.Properties.VariableNames{2:end};
But I wouldn't recommend it. Use the proper syntax for accessing variable names, which is the '()' operator.
  1 Comment
Alan on 22 Sep 2014
Thank You for the insight. I think this answers my question...

Sign in to comment.

More Answers (0)


Community Treasure Hunt

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

Start Hunting!