MATLAB Answers

How can I display multiple images in one figure window using for loop?

16 views (last 30 days)
Lauren Pitts
Lauren Pitts on 30 Jul 2019
Commented: Adam Danz on 31 Jul 2019
Is there a way for me to be able to read/display 100 images (0001.png - 0100.png) without having to type them all manually like below? All 100 images are in a folder if that helps (C:\Users\pittsl\Desktop\Matlab\train\cup).
files = {'0001.png', '0002.png','0003.png','0004.png','0005.png',};
for K = 1 : 5
this_image = imread(files{K});
ax = subplot(1, 5, K);
imshow(this_image, 'Parent', ax);
end

  0 Comments

Sign in to comment.

Accepted Answer

Adam Danz
Adam Danz on 30 Jul 2019
Edited: Adam Danz on 30 Jul 2019
% Inputs: folder and file extension
% Will plot all files with the chosen extension in the chosen folder
folder = 'C:\Users\pittsl\Desktop\Matlab\train\cup';
ext = 'png'; %extension, no dot
% Get list of all files
content = dir(folder);
allfiles = {content.name};
isExt = endsWith(allfiles,['.',ext],'IgnoreCase',true); % req. r2016b or later https://www.mathworks.com/help/matlab/ref/endswith.html
files = allfiles(isExt);
% Determine subplot layout
nImages = numel(files);
dimN = ceil(sqrt(nImages));
dimM = ceil(nImages/dimN);
nrows = min(dimN, dimM);
ncols = max(dimN, dimM);
% Plot them
for K = 1:nImages
this_image = imread(fullfile(folder,files{K}));
ax = subplot(nrows,ncols, K);
imshow(this_image, 'Parent', ax);
end

  3 Comments

Stephen Cobeldick
Stephen Cobeldick on 31 Jul 2019
It would be simpler just to specify the dir file name with wildcard and extension:
content = dir(fullfile(folder,'*.png'));

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by