【问题标题】:How to save a numeric value in a specified location of a CSV file inside for loops in MATLAB?如何将数值保存在 MATLAB 中 for 循环内的 CSV 文件的指定位置?
【发布时间】:2023-04-11 00:55:02
【问题描述】:

我想这样做是因为否则我会用完内存来将值保存在矩阵中,因为矩阵的维度会增加。

例如,

for a=1:10000
   for b=1:10000
      M(a,b)=rand;
   end
end

这里,系统内存不足,因为它无法存储 10000x10000 矩阵。

所以,我想继续将 for 循环中的 (a,b)'th 值写入 csv 文件(或 xls 文件等)的第 (a,b)'th 单元格。我该怎么做?

我想要这样的东西:

for a=1:10000
   for b=1:10000
      xlswrite1('file.xls',a,b,rand); % better if I can get a solution with csvwrite, as I prefer CSVs to work with
   end
end

但这显然行不通。它给出的错误是:

Error using evalin
Undefined function or variable 'Excel'.

Error in xlswrite1 (line 2)
Excel=evalin('caller','Excel');

那么当我根据this文章添加以下几行时,

Excel = actxserver ('Excel.Application');
File='datafile.xls';
if ~exist(File,'file')
ExcelWorkbook = Excel.workbooks.Add;
ExcelWorkbook.SaveAs(File,1);
ExcelWorkbook.Close(false);

它给出了这个错误:

Error using xlswrite1 (line 82)
Range argument must a string of Excel A1 notation.

谁能提出一个简单的解决方案?到目前为止,我无法从我的在线搜索中找到任何内容。

【问题讨论】:

    标签: matlab csv for-loop memory optimization


    【解决方案1】:

    您可以使用 dlmwrite 来做到这一点。但我建议你逐行而不是逐个元素地编写。

      N = 100 ;
      M = zeros(N,N) ;
      filename = 'test.csv';
      for a=1:N
         for b=1:N
            M(a,b)=rand;
         end
         dlmwrite(filename,M(a,:),'-append')
      end
    

    如果您不想制作矩阵M,则制作行并将它们写入您的文件:

    N = 100 ;
    M = zeros(1,N) ;
    filename = 'test.csv';
    for a=1:N
       for b=1:N
          M(1,b)=rand;
       end
       dlmwrite(filename,M(1,:),'-append')       
    end
    

    【讨论】:

    • 但是在这里你无论如何都在创建矩阵 M,所以内存正在被占用,这是我想逃避的。
    • 在答案中添加。
    • 好的,谢谢。有用。但我有一个辅助问题。我注意到使用 dlmwrite,代码需要 101.95 秒才能完成运行,而只有 M(即不写入文件)需要 67.53 秒。那是 50.97% 更长的时间!为什么写入文件时时间会急剧增加?我知道写入文件需要时间,但是这么多?是不是每次调用dlmwrite 时,它都会检查文件是否存在等?如果是这样,是否可以通过例如在开始时创建和打开文件而不检查文件是否存在于循环中来优化此文件写入?
    • 这个选项带有 fopen/fprintf 但不带有 dlmwrite...我想。
    • 好的。那么,你知道如何让这段代码不花这么长时间运行吗?它只在 M=100 时花费这个时间。就我而言,M 实际上 = 10000。因此,以这个速度完成运行需要数周时间!
    【解决方案2】:

    我建议使用 fprintf

    N = 100 ;
    M = zeros(1,N) ;
    filename1 = 'test1.csv';
    t1 = tic ;
    for a=1:N
       for b=1:N
          M(1,b)=rand;
       end
       dlmwrite(filename1,M,'-append')
    
    end
    t1 = toc(t1) ;
    
    filename2 = 'test2.csv';
    M = zeros(1,N) ;
    t2 = tic ;
    fid = fopen(filename2,'w') ;
    for a=1:N
       for b=1:N
          M(1,b)=rand;
       end
       fprintf(fid, [repmat(' %f ', 1, N) '\n'], M') ;
    
    end
    fclose(fid) ;
    t2 = toc(t2) ;
    
    fprintf('time taken using dlmwrite:%f\n',t1)
    fprintf('time taken using fprintf:%f\n',t2)
    

    【讨论】:

    • fprintf 花了我 67.90 秒,与dlmwrite 几乎相同。
    • 对我来说....对于 N = 1000;使用 dlmwrite:13.147731 所用时间,使用 fprintf:3.186585 所用时间
    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多