2009-11-06 53 views
4

我有這樣一個循環:如何在MATLAB中使用循環變量創建一個字符串?

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不起作用。 這個怎麼辦?

回答

5

另一個選擇將是功能SPRINTF

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

你嘗試:

int2str(i) 
3

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

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

+1

int2str(i)not int2str(1) – MatlabDoug 2009-11-06 15:04:23

相關問題