如何将单元格数组附加到.txt文件?

时间:2010-12-30 17:53:47

标签: matlab file-io text-files cell-array

我之前曾询问过including matrices and strings in a .txt file。我现在需要将细胞附加到它上面。从我之前的问题:

str = 'This is the matrix: ';
mat1 = [23 46; 56 67];
fName = 'output.txt';
fid = fopen(fName, 'w');
if fid >= 0
    fprintf(fid, '%s\n', str);
    fclose(fid);
end
dlmwrite(fName, mat1, '-append', 'newline', 'pc', 'delimiter', '\t');

现在我想附加一个字符串:'删除的标识符是',然后是它下面的单元格数组:

'ABC' [10011] [2]
'DEF' [10023] [1] 

一些相关链接:

http://www.mathworks.com/help/techdoc/ref/fileformats.htmlhttp://www.mathworks.com/support/solutions/en/data/1-1CCMDO/index.html?solution=1-1CCMDO

2 个答案:

答案 0 :(得分:3)

不幸的是,您不能使用DLMWRITECSVWRITE等函数来编写数据的单元格数组。但是,要获得所需的输出,您仍然可以使用FPRINTF的单个调用,但是您必须指定单元格数组中所有条目的格式。在my answer to your previous question的基础上,您可以添加以下附加行:

str = 'The removed identifiers are: ';   %# Your new string
cMat = {'ABC' 10011 2; 'DEF' 10023 1};   %# Your cell array
fid = fopen(fName,'a');                  %# Open the file for appending
fprintf(fid,'%s\r\n',str);               %# Print the string
cMat = cMat.';                          %'# Transpose cMat
fprintf(fid,'%s\t%d\t%d\r\n',cMat{:});   %# Print the cell data
fclose(fid);                             %# Close the file

新文件内容(包括旧示例)将如下所示:

This is the matrix: 
23  46
56  67
The removed identifiers are: 
ABC 10011   2
DEF 10023   1

答案 1 :(得分:0)

您可以使用文件交换中的cellwrite。阅读来自 Francis Barnhart Writing Mixed Data With MATLAB,可能值得一看的是,写作的创建者。

将cellwrite的签名更改为接受文件句柄应该是一项可行的任务。允许将数据附加到现有文件。