2017-09-25 80 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

相关问题