2015-12-01 237 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');在你上面有代碼。

相關問題