【问题标题】:How do I create a string using a loop variable in MATLAB?如何在 MATLAB 中使用循环变量创建字符串?
【发布时间】:2009-11-06 13:31:33
【问题描述】:

我有一个这样的循环:

for i=1:no

  %some calculations

  fid = fopen('c:\\out.txt','wt');
  %write something to the file
  fclose(fid);

end

我希望将数据写入不同的文件,如下所示:

  • 对于i=1,数据写入out1.txt
  • 对于i=2,数据写入out2.txt
  • 对于i=3,数据写入out3.txt

执行'out'+ i 不起作用。 如何做到这一点?

【问题讨论】:

    标签: string matlab file-io


    【解决方案1】:

    另一个选项是函数SPRINTF

    fid = fopen(sprintf('c:\\out%d.txt',i),'wt');
    

    【讨论】:

      【解决方案2】:

      filename = strcat('out', int2str(i), '.txt');

      【讨论】:

        【解决方案3】:

        你试过了吗:

        int2str(i)
        

        【讨论】:

          【解决方案4】:

          更简单:

          for i=1:no
            %some calculations
            fid = fopen(['c:\out' int2str(i) '.txt'],'wt');
            %write something to the file
            fclose(fid);
          
          end
          

          附言。我不相信 Matlab 字符串需要转义,除了 '' (除非它是 *printf 样式函数的格式字符串)

          编辑:见评论@MatlabDoug

          【讨论】:

            猜你喜欢
            • 2019-01-04
            • 2013-01-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-06-06
            • 1970-01-01
            • 2018-04-15
            • 2022-08-04
            相关资源
            最近更新 更多