首页 > 解决方案 > MATLAB 写入字符串,然后将表写入文件

问题描述

我需要将一个字符串和一个表格写入一个文本文件。该字符串包含表中数据的描述,但不是表的标题。我正在使用 R2019a,我猜这意味着“附加”可写选项不起作用?请参阅下面的示例数据:

% 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')

我收到此错误:

Error using writetable (line 155)
Wrong number of arguments.

有人对如何进行有任何建议吗?

谢谢!

标签: matlab

解决方案


有点hacky,但这是一个想法。

  • 使用table2cell将现有表转换为元胞数组。
  • 在前面添加一行包含您的字符串的单元格,然后是空单元格。
  • 使用cell2table将元胞数组转换回表格,并将新表格写入文件。

load cereal.mat;
table =  table(Calories, Carbo, Cups, Fat, Fiber, Mfg, Name, Potass);
s = {'This is a string about the cereal table'};
filename = "dummyoutput.sfc";

new_table = cell2table([[s repmat({''},1,size(table,2)-1)] ; table2cell(table)]);
writetable(new_table,filename,'FileType','text','WriteVariableNames',0,'Delimiter','tab');

>> !head dummyoutput.sfc
This is a string about the cereal table                          
70  5   0.33    1   10  N   100% Bran   280 
120 8   -1  5   2   Q   100% Natural Bran   135 
70  7   0.33    1   9   K   All-Bran    320 
50  8   0.5 0   14  K   All-Bran with Extra Fiber   330 
110 14  0.75    2   1   R   Almond Delight  -1 
110 10.5    0.75    2   1.5 G   Apple Cinnamon Cheerios 70 
110 11  1   0   1   K   Apple Jacks 30 
130 18  0.75    2   2   G   Basic 4 100 
90  15  0.67    1   4   R   Bran Chex   125 

推荐阅读