2017-09-25 83 views
0

我有兩個類似的問題,但對於不同的目的。Matlab。寫文本文件或創建它,如果它不存在。保存數據在目錄或創建它,如果不存在

1)我怎麼能告訴MATLAB的文本文件寫,如果不存在,創建它嗎?基本的代碼以提高會是這樣的:

fileID = fopen('results.txt','w'); 
fprintf(fileID, 'Name\t\t\t\t\t\t\t\t\t%%variation\t\tSteady-state\n'); 
fclose(fileID); 

1)同樣的事情,但是,當我保存的數字,我想將它們保存在一個工作的子目錄,但如果它不存在它應該創建它。基本的代碼以提高會是這樣的:

fig=figure; set(fig, 'Visible', 'off'); 
plot(...); xlabel(...); ylabel(...); legend(...); 
saveas(fig,s3) 

,其中S3是

s3 = char(strcat(s1(1),'.png')); %concatenate .png and convert to string 

我怎麼能告訴它保存到不同的目錄?

非常感謝你,如果該文件不存在,如果該文件存在逃跑內容

回答

0

你的第一個代碼工作正常。我想,第一個問題是,你想,如果文件已經存在,保存的內容,所以:

if exist('results.txt')==2 
    fileID = fopen('results.txt','a'); % open exist file and append contents 
else 
    fileID = fopen('results.txt','w'); % create file and write to it 
end 

對於第二個問題:

if exist('SubDir')~=7 % if there is not a sub-directory named "SubDir", make it 
    mkdir('SubDir'); 
end 
saveas(fig,fullfile('SubDir',s3)) 
+0

WOW!非常感謝你。 現在,它的作品,我只需要創建一個用戶可以在其中選擇路徑的接口^^」。 這是要帶我一段時間。再次感謝 –

+0

如果你想要讓用戶選擇的路徑,使用'uiegtdir'- https://www.mathworks.com/help/matlab/ref/uigetdir.html – Adiel

相關問題