Table VariableNames Property Won't Print Directly

조회 수: 3 (최근 30일)
Alan
Alan 2014년 9월 22일
댓글: Alan 2014년 9월 22일
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?

채택된 답변

Guillaume
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.
  댓글 수: 1
Alan
Alan 2014년 9월 22일
Thank You for the insight. I think this answers my question...

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Spreadsheets에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by