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

23 views (last 30 days)
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

Accepted Answer

Matt J
Matt J on 5 Feb 2023
Edited: Matt J on 5 Feb 2023
One possibility:
saveas(gcf, fullfile(OutputFigures, "FIG"+i) );
  1 Comment
Macy
Macy on 5 Feb 2023
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!