MATLAB。写入文本文件或创建它,如果它不存在。将图形保存在目录中,如果不存在则创建它

Posted

技术标签:

【中文标题】MATLAB。写入文本文件或创建它,如果它不存在。将图形保存在目录中,如果不存在则创建它【英文标题】:Matlab. Write text file or create it if it doesn't exist. Save figures in directory or create it if it doesn't exist 【发布时间】:2017-09-25 09:11:59 【问题描述】:

我有两个类似的问题,但目的不同。

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

如何告诉它保存到不同的目录?

非常感谢

【问题讨论】:

【参考方案1】:

如果文件不存在,您的第一个代码可以正常工作,如果文件存在,则运行内容。我想第一个问题是如果文件已经存在,你想保留内容,所以:

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))

【讨论】:

哇!非常感谢你。现在它可以工作了,我只需要创建一个界面,用户可以从中选择路径^^'。这需要我一些时间。再次感谢 如果想让用户选择路径,使用uiegtdir-mathworks.com/help/matlab/ref/uigetdir.html

以上是关于MATLAB。写入文本文件或创建它,如果它不存在。将图形保存在目录中,如果不存在则创建它的主要内容,如果未能解决你的问题,请参考以下文章

FMDB databaseWithPath:不写入磁盘

如何将MATLAB运行结果写入txt文件

C#:检查文件是不是存在 - 进程无法访问文件错误

如果它不存在,如何创建一个 CSV 文件,然后只附加到它 Python

python文本操作

matlab中使用fwrite将1到10写入文本文件中,再用fread读取该文本文件中的数据,怎么写程序