将单元格写入文本文件

Write cell into a text file

我有一个 39x4 的单元格:

'ID'    'x' 'y' 'z'
459     34  -49 -20
464     36  -38 -22
639     40  -47 -27
719     35  -52 -20
725     42  -45 -18
727     46  -47 -26
...

我想把所有这些都写到一个文本文件中。我尝试了以下方法:

fileID = fopen('test2.txt','w');
formatSpec='%s %d %d %d';
fprintf(fileID,formatSpec,P{:});
fclose(fileID);

但是,如果我这样做,我会得到一个错误,即没有为 'cell' 输入定义 fprintf。我看过几个像这样的关于如何 print a cell array as .txt in Matlab this one about how to write cell array of combined string and numerical input into text file 的例子,但如果不进行一些笨拙的修改,它们似乎不太适合。

有人可以帮忙吗?

您的错误是由于元胞数组的第一行仅包含字符串而其他行仅包含数字。您的格式说明符当前假定每行要写入的第一个元素是字符串,而其他元素是整数。您必须适应一种特殊情况,即写入第一行仅包含字符串。

像这样的东西应该可以工作:

%// Open the file for writing
fileID = fopen('test2.txt','w');

%// First write the headers to file
fprintf(fileID, '%s %s %s %s\n', P{1,:});

%// Transpose because writing is done in column-major order
Pt = P.'; %'

%// Now write each row to file
fprintf(fileID, '%d %d %d %d\n', Pt{:,2:end});

%// Close the file
fclose(fileID);

请注意,第一行的格式说明符全部由字符串组成,而后几行的格式说明符仅由整数组成。另请注意,我需要 转置 元胞数组,因为使用 fprintf 自然会以 column-major 顺序写入矩阵,以便将矩阵写入 [=21] =] 时尚,打印前需要换位,我们还需要访问数据的列而不是行来容纳。

错误很可能是由于您的代码中的以下行引起的:

fprintf(fileID,formatSpec,P{:}); % P{:} returns all the cells in P matrix

此外,您指定的 formatSpec 不适用于所有行,因为第一行的格式不同。您将需要两次调用 fprintf 作为:

fprintf(fileID,'%s %s %s %s\n',P{1,:});
fprintf(fileID,'%d %d %d %d\n',P{2:end,:});