【问题标题】: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');
【解决方案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