Clear Filters
Clear Filters

I made a folder with 12 .fig files, I am attempting to convert these to jpeg using a loop.

2 views (last 30 days)
I have tried multiple loops and commands but I am new to matlab and have still not been able to figure it out.
figs = openfig('Figures');
for K = 1 : length(figs)
filename = sprintf('figure_%02d.jpg', K);
saveas(figs(K), filename);
end
This is what I have.
Error using load
Unable to read file 'Figures'. Input cannot be a directory.
Error in matlab.graphics.internal.figfile.FigFile/read (line 31)
hgDataVars = load(filename, '-mat', '-regexp', '^hg[M]');
Error in matlab.graphics.internal.figfile.FigFile
Error in loadFigure (line 31)
FF = matlab.graphics.internal.figfile.FigFile(fullpath);
Error in openfig>localOpenFigure (line 75)
h = loadFigure(filename, visibleAction);
Error in openfig (line 40)
figOut = localOpenFigure(filename, reuse, visibleAction);
Error in P2B (line 1)
figs = openfig('Figures');
These are the errors I am getting and the pictures are the figures the the folder.

Accepted Answer

DGM
DGM on 4 Apr 2024
Edited: DGM on 4 Apr 2024
Maybe something more like this.
D = dir('Figures/*.fig'); % use dir() to get directory contents
for K = 1:numel(D)
hf = openfig(fullfile(D.folder,D.name)); % get the full name
filename = sprintf('figure_%02d.png', K); % don't use JPG for anything
saveas(hf, filename); % save the opened figure
close(hf) % close the opened figure instead of creating a pile of them
end
... assuming there are less than 100 .fig files.
  5 Comments

Sign in to comment.

More Answers (1)

Mitchell Thurston
Mitchell Thurston on 4 Apr 2024
You can do it by running this code while inside the Figures directory
files = ls; % get filenames of everything in that directory
K = 0;
for i = 1:length(files(:,1))
[~,~,ext] = fileparts(files(i,:));
if strcmp(strip(ext),'.mat')
K = K+1;
fig = openfig(files(i,:));
filename = sprintf('figure_%02d.jpg', K);
saveas(fig, filename);
end
end
Also, if the figures are generated by P2B.m, you should be able to get all the figures outputted by publishing that script.

Categories

Find more on Printing and Saving in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!