Write string and table (in that order) to text file

15 ビュー (過去 30 日間)
Melissa Buechlein
Melissa Buechlein 2020 年 7 月 13 日
回答済み: Melissa Buechlein 2020 年 7 月 13 日
I need to write a string and a table to one text file. The string contains a description of the data in the table, but is not the headers for the table. I am using R2019a which I guess means the "Append" writetable option does not work? Please see my example data below:
% Load data
load cereal.mat;
table = table(Calories, Carbo, Cups, Fat, Fiber, Mfg, Name, Potass);
string = {'This is a string about the cereal table'};
filename = "dummyoutput.sfc";
% How I tried to do this (which does not work!)
fid = fopen(filename, 'w', 'n');
fprintf(fid, '%s', cell2mat(string))
fclose(fid);
writetable(table, filename, 'FileType', 'text', 'WriteVariableNames', 0, 'Delimiter', 'tab', 'WriteMode', 'Append')
I get this error (because 'WriteMode' was introduced in R2020a)
Error using writetable (line 155)
Wrong number of arguments.
Does anyone have a workaround for this?
Thanks!

採用された回答

Melissa Buechlein
Melissa Buechlein 2020 年 7 月 13 日
I doubt this is the most efficent workaround, but it solved my issue.
writetable(table, filename, 'WriteVariableNames', 0,...
'FileType', 'text', 'Delimiter', 'space', 'QuoteStrings', false)
content = fileread(filename);
% Update the file
content = {cell2mat(header{:}); content};
% go back and remove empty lines
newcontent = regexprep(content, {'\r', '\n\n+'}, {'', '\n'});
% write the full file
writecell(newcontent, filename, 'FileType', 'text', 'QuoteStrings', false);

その他の回答 (1 件)

Takumi
Takumi 2020 年 7 月 13 日
編集済み: Takumi 2020 年 7 月 13 日
  4 件のコメント
Takumi
Takumi 2020 年 7 月 13 日
編集済み: Takumi 2020 年 7 月 13 日
How about writing in fprintf instead of writetable?
Melissa Buechlein
Melissa Buechlein 2020 年 7 月 13 日
My output table is not all of the same format, so I cannot turn it into an array. I am also unfamiliar with how to make fprintf work with cells. However, I was able to come up with a work around! Thanks for your suggestions!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by