首页 > 解决方案 > 将带有数字的单元格保存到文本文件

问题描述

我有不同长度和数字的单元格数组 A 和 B。

A={1:0.5:5;1:0.5:2};
B={1:0.5:6;1:0.5:9};
C= [A;B];

我想将这些元胞数组组合成一个元胞数组 C,它看起来像这样:

C =

  4×1 cell array

    {1×9  double}
    {1×3  double}
    {1×11 double}
    {1×17 double}

然后,我想把它保存到一个文本文件中,应该是这样的:

1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000    4.5000    5.0000
1.0000    1.5000    2.0000
1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000    4.5000    5.0000    5.5000    6.0000
1.0000    1.5000    2.0000    2.5000    3.0000    3.5000    4.0000    4.5000    5.0000    5.5000    6.0000   6.5000    7.0000    7.5000    8.0000    8.5000    9.0000

到目前为止,我只找到了文本或相同大小数组的代码。这是我的尝试,它不起作用:

fid = open('filename.txt', 'wt');
fprintf(fid, '%f',C{:})
close(fid)

标签: matlabcelltxt

解决方案


我相信问题可能出在您为 指定的格式中fprintf,因为我相信使用 only'%f'会在每一行上打印一个数字。

这样做的一种方法是:

    fid = fopen('filename.txt', 'wt');
    for i = 1:length(C)
        fmt = repmat('%f ',size(C{i})); % this only adds one whitespace in between numbers
        fmt = [fmt,'\n']; % remember to add a new line
        fprintf(fid,fmt,C{i});
    end
    fclose(fid);

推荐阅读