How do I save for loop plots to a figure directory?

35 ビュー (過去 30 日間)
Macy
Macy 2023 年 2 月 5 日
コメント済み: Macy 2023 年 2 月 5 日
I am completely new to MatLab. I was intructed to create a string variable that contains the name of a directory I made (a folder called OutputFigures which is found in C:\Users\sfai\Documents\MATLAB\OutputFigures).
How do I make this string variable? I tried the following but I am not sure if it is correct:
OutputFigures = 'C:\Users\sfai\Documents\MATLAB\OutputFigures';
When trying to save plots to this folder, I kept getting an error message stating that the file and/or folder path was invalid or missing. It only worked when I used 'OutputFigures/' which you will see below.
Then I made the following 5 plots using a forloop. I was instructed to save the plots (with corresponding figure names, Fig.1, Fig.2 etc) to the directory I made. I am getting stuck on saving my plots to the directory I made, OutputFigures.
Hints I was given to use: Hint#1: Use the "saveas(gcf,...) function to save the file. Hint#2: Concatenate strings to create the correct file and folder path.
I found out one way to save the plots in the correct location with correct names:
saveas(h,sprintf('OutputFigures/FIG%d.png',i));
However, I don't think this "concatenates strings".
When I try the following:
saveas(gcf, [strcat('Figure #', num2str(i), '.png')]);
I get the plots, but I don't know how to save them to the directory I created.
And when I try to save them like so, it only saves one figure titled "name":
name = [strcat('Figure #', num2str(i), '.png')];
% saveas(gcf, 'OutputFigures/name.jpg');
Any help is greatly appreciated. Here is the complete code:
plot_points = [1:5]
color = ["r", "g", "b", "m", "b"];
OutputFigures = 'C:\Users\sfai\Documents\MATLAB\OutputFigures';
for i=1:5
h=figure
plot(plot_points,plot_points,color(i))
xlabel('X')
ylabel('Y')
title(strcat({'Figure # '}, num2str(i)))
%% How can I us saveas(gcf,...) function to save the file and concatenate strings to create the correct file and folder path?
end

採用された回答

Matt J
Matt J 2023 年 2 月 5 日
編集済み: Matt J 2023 年 2 月 5 日
One possibility:
saveas(gcf, fullfile(OutputFigures, "FIG"+i) );
  1 件のコメント
Macy
Macy 2023 年 2 月 5 日
Thank you so much! I also found that my initital string variable OutputFigures was going to a new folder instead of the one I wanted it to go to but when changing it to simply OutputFigures = 'OutputFigures/'; it saves it in the right folder.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeEnvironment and Settings についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by