matlab - 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.
有人对如何进行有任何建议吗?
谢谢!
解决方案
有点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
推荐阅读
- javascript - 无效参数 - Edge 浏览器中的 Google 地图错误
- blueprism - 在 Blue Prism RPA 中每 30 秒在后台安排进程
- javascript - Laravel + VueJs:MPA 架构
- python - 从具有坐标和值的字典构建 numpy 矩阵
- regex - 正则表达式隐式 AND 不起作用,但显式 OR 起作用
- jquery - JQuery 用 id 替换类
- javascript - 如何避免在 react native webview 中弹出。?
- visual-studio-code - 为什么`cargo build`不能在VS Code中编译structopt-derive?
- javascript - wpbackery 视觉作曲家 5.4.7 前端编辑器不工作仅显示徽标
- c# - 具有动态子菜单的水平菜单的 SplitView 替代方案