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