I want to compare a given input image from a set of images and display the corresponding image

%function imgDB()
img=imread('1.jpg');
a=['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
for i=1:size(a)
if (img==a(i))
disp('YES');
else
disp('NO')
break
end
end

 Accepted Answer

You need to put the different filenames into a cell array. If you concatenate them into an ordinary array, you just get a long string. So instead of
a=['1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'];
you need
a={'1.jpg','2.jpg','3.jpg','4.jpg','5.jpg'};
Instead of size(a) at the top of the for loop, you should use length(a). (size(a) returns both dimensions, but you only want the length.)
To get the file name inside the loop, now a is a cell array you need to use a{i} rather than a(i).
It's no good comparing your image with a file name - you need to read the second image in, as you did for img. So instead of
if (img==a(i))
you need
if (img==imread(a{i}))
It's preferable to use isequal(x,y) rather than x==y in a test like this, though the code above will work.
Finally, the code as modified will always print TRUE on the first iteration because you compare 1.jpg with itself, and will exit as soon as a non-matching image is found, without checking the remaining files in the list - I assume that's what you want.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!