Image File Reading, Error with Strings...?

1 view (last 30 days)
Daniel Lee
Daniel Lee on 17 Oct 2016
Answered: Image Analyst on 18 Oct 2016
I am trying to read an image file (in the same matlab folder as the code).
Right now, my code is:
shapes = {'Tri', 'Rec', 'Cir', 'Oct'};
num = 1:20;
file = strcat(shapes(i), num2str(num(k)), '.png');
I = imread(file);
However, I am getting an error that the file name has to be a string. I also tried making an array like this:
nums = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'};
And instead used
file = strcat(shapes(i), nums(k), '.png');
But still I got the same error.
If anyone can help with this problem it would be great. ^^
P.S. Is there an easy way to import a file that is in a folder that is inside the Current Folder? Thanks.

Answers (1)

Image Analyst
Image Analyst on 18 Oct 2016
Try this:
shapes = {'Tri', 'Rec', 'Cir', 'Oct'};
num = 1:20;
% Loop over every shape and every number in "num"
for i = 1 : length(shapes)
for k = 1 : length(num)
thisNumber = num(k); % Extract the number.
% Construct the full file name.
thisFileName = sprintf('%s%d.png', shapes{i}, thisNumber);
fullFileName = fullfile(pwd, thisFileName);
fprintf('Looking for %s\n', fullFileName);
% Check if the file exists.
if exist(fullFileName, 'file')
fprintf(' Found %s\n', thisFileName);
thisImage = imread(file);
% Now do something with thisImage.
else
fprintf(' Did not find %s\n', thisFileName);
end
end
end

Community Treasure Hunt

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

Start Hunting!