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

34 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Environment and Settings 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by