如何在MATLAB中使用循环变量创建字符串?

时间:2009-11-06 13:31:34

标签: string matlab file-io

我有一个这样的循环:

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不起作用。 如何做到这一点?

4 个答案:

答案 0 :(得分:5)

另一种选择是函数SPRINTF

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

答案 1 :(得分:3)

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

答案 2 :(得分:1)

你有没有尝试过:

int2str(i)

答案 3 :(得分:0)

更简单:

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

end

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

编辑:见评论@MatlabDoug