【问题标题】:Matlab - Writing Text and Numeric Data to a File in a LoopMatlab - 将文本和数字数据循环写入文件
【发布时间】:2013-08-23 03:05:49
【问题描述】:

我已经用谷歌搜索了很多次来解决我关于写入/输出到文件的特殊情况,但没有取得多大成功。

我有一个 for 循环,它生成 1 个单元矩阵和 1 个常规矩阵。对于每个循环,单元矩阵可以是可变长度的。假设尺寸为 ,单元矩阵存储以下字符串:

Aggregated Day, AggreVal from Curve, Val3_Name, Val4_Name, Val5_Name

下一个循环的单元矩阵可以有不同的内容和大小。

数值矩阵与单元矩阵大小相同,表示单元矩阵中名称对应的值。因此,对于这个循环,它的大小为 1x5,并将值存储为:

1.3, 1300, 14, 15, 16

我想在生成上述单元格和数字矩阵时将它们写入一个单个文件(最好是 excel 或 txt 文件以供将来操作)。首先,我想输出单元矩阵,然后是该数字矩阵。其次是第二个循环的单元矩阵,依此类推。

我记得在 C++ 中通过以附加模式打开文件非常容易,但在 Matlab 中似乎很棘手。我尝试过使用 xlswrite、dlmwrite、xlsappend 等,但到目前为止没有任何效果。

因此,输出文件将如下所示:

Loop1
Aggregated Day, AggreVal from Curve, Val3_Name, Val4_Name, Val5_Name
1.3, 1300, 14, 15, 16

Loop2
Aggaed Dy, AgeVal fm Curve, China, Val4_Name, Brazil
1.453, 1300, 1774, 1115, 1613

谢谢

【问题讨论】:

    标签: matlab append


    【解决方案1】:

    在所有循环完成之前,您能否避免关闭文件,即:

    fid = fopen('filename.txt','w');
    
    % Loop stuff, adding lines to your file
    
    fclose(fid);
    

    看起来您想要的输出类型是自定义格式,而不是 xls 文件,它采用类似表格的结构。尝试使用 fprintf 打印您的数据:

    foo = {'abc','def','ghi'};
    foo2 = [1 2 3 4];
    fid = fopen('foo.txt','w');
    fprintf(fid, '%s ', foo{:});
    fprintf(fid, '\n');
    fprintf(fid, '%f ', foo2);
    fprintf(fid, '\n');
    fclose(fid)
    

    【讨论】:

    • 您的代码不起作用。我是新手,所以我现在想弄清楚为什么它不起作用。
    • 抱歉,我忘记在 fprintf 中包含 'w' 参数(它告诉 Matlab 你想“写入”文件,而不是从中读取)。
    【解决方案2】:

    我会这样做:

    A{1} = {'Aggregated Day', 'AggreVal from Curve', 'Val3_Name', 'Val4_Name', 'Val5_Name'}
    A{2} = {1.3, 1300, 14, 15, 16};
    B = cat(1,A{:});
    xlswrite(filename,B);
    

    【讨论】:

    • 它在for循环中不起作用,因为以前的数据被最新循环的信息擦除和覆盖。
    【解决方案3】:
    %s={'Aggregated Day', 'AggreVal from Curve', 'Val3_Name', ...
       'Val4_Name', 'Val5_Name'};
    
    %n=[1.3, 1300, 14, 15, 16];
    
    filename='myfile.xlsx'; % Change it to myfile.txt if needed for text version
    
    % the trick is to retain the row number to append contents
    
    %N = no. of entries.
    for k = 1:2:N                %Sheet        %Row
        xlswrite( filename, s ,    1,    sprintf('A%d',k)   )
        xlswrite( filename, n ,    1,    sprintf('A%d',k+1) )
    end
    

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-13
      • 2014-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多