【问题标题】:Matlab. Write text file or create it if it doesn't exist. Save figures in directory or create it if it doesn't existMATLAB。写入文本文件或创建它,如果它不存在。将图形保存在目录中,如果不存在则创建它
【发布时间】: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

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

非常感谢

【问题讨论】:

    标签: matlab fopen save-as


    【解决方案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
    猜你喜欢
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2021-01-31
    • 2022-01-11
    • 2017-06-26
    • 1970-01-01
    • 2016-03-17
    相关资源
    最近更新 更多