2015-12-01 223 views
0

如何将字符串文件名包含到fopen函数中?请参阅下面的代码和评论。MATLAB - 如何将字符串作为函数的参数

for i=1:5 
    filename = strcat('Cali',num2str(i)); 
    %first iteration: filename = Cali1   
    %instead of result.txt there should be Cali1.txt in the following statement, but i want to achieve this by using the string filename 

    fid = fopen('results.txt', 'wt'); 
    fprintf(fid, 'write something'); 
    fclose(fid); 
end 
+5

这是[在文档中明确指出](http://www.mathworks.com/help/matlab/ref/fopen.html#btrnoom-1)。将它作为参数传递给函数。 – excaza

+0

可能还需要添加文件扩展名...'filename = strcat('Cali',num2str(i),'.txt'); ' – RTL

+0

那简单!谢谢 – d4rty

回答

2

这是Matlab的基本功能。你应该仔细阅读手册。这就是说,在这里您需要的代码:

for i=1:5 
    fid = fopen(['Cali' num2str(i) '.txt'], 'wt'); 
    fprintf(fid, 'write something'); 
    fclose(fid); 
end 

如果你想使用strcat,只需添加一行filename = strcat('Cali', num2str(i), '.txt');在你上面有代码。

相关问题