Table VariableNames Property Won't Print Directly
3 ビュー (過去 30 日間)
古いコメントを表示
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'];
fprintf(MLID,fstr,HTable.Properties.VariableNames(2:end));
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'];
fprintf(MLID,fstr,HTable.Properties.VariableNames{2:end});
But the following code works:
fstr = [repmat('%s,',1,length(HTable.Properties.VariableNames)-2),'%s\n'];
hdrs = HTable.Properties.VariableNames(2:end);
fprintf(MLID,fstr,hdrs{:});
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?
0 件のコメント
採用された回答
Guillaume
2014 年 9 月 22 日
編集済み: Guillaume
2014 年 9 月 22 日
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.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Spreadsheets についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!