【问题标题】:Write cell into a text file将单元格写入文本文件
【发布时间】:2016-01-19 19:28:00
【问题描述】:

我有一个 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);

但是,如果我这样做,我会收到 fprintf 没有为“单元格”输入定义的错误。我已经看到了几个像这样的例子,关于如何print a cell array as .txt in Matlab 这个例子是关于如何write cell array of combined string and numerical input into text file,但如果没有一些笨拙的修改,它们似乎不太适合。

有人可以帮忙吗?

【问题讨论】:

    标签: matlab text cell


    【解决方案1】:

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

    这样的事情应该可以工作:

    %// 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 自然会以列优先顺序写入矩阵,因此为了以行优先方式写入矩阵,之前需要转置打印,我们还需要访问数据的列而不是要容纳的行。

    【讨论】:

    • 谢谢你,rayryeng。处理标题的行不起作用。当我运行 fprintf(fileID, '%s %s %s %s\n', P{1,:}); 时,我仍然收到 fprintf 未为单元格输入定义的错误。我错过了什么吗?
    • @A.Rainer 该代码对我有用.... 我声明 P 是一个单元格数组,就像您在代码中使用的那样。我很困惑你为什么会收到这个错误。
    • 这也可能与您使用的 MATLAB 版本有关。您使用的是哪个 MATLAB 版本?
    • 我使用的是 2014a。如果我做whos P,我会得到Name Size Bytes Class Attributes: P 40x4 19200 cell 。如果我不在 P 中包含标题并跳过标题行,其他一切正常。
    • 我的代码确实有错误。你的代码是正确的。
    【解决方案2】:

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

    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,:});
    

    【讨论】:

    • 请注意fprintf 使用矩阵以列优先顺序访问元素。您需要转置P,然后将第二列访问到最后一列,以便将其正确写入文件。
    猜你喜欢
    • 2013-01-11
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    相关资源
    最近更新 更多