How to compare two matrices of diffrent dimensions by looping.

Basically, i want to scan a small matrix over bigger matrix and then compare it's elements one by one for greater or less than bigger matrix.The comparison can be done in either way through column or through row.

3 Comments

If you have
a=[1 2;3 4] % the small matrix
%and
b=[1 5 6;4 0 8;11 12 0] % the big matrix
What should be the result?
the small matrix should be compared with that of big matrix for greater than or equal to. The result is to find a match between the elements of two matrix's and store their positions(index) after being compared. The result i want is; 1=1,match found,store it 5>2,store it's position and the element 4>3,store it 0<4,neglect it
@Sonny: Please answer Azzi's question. Do not describe how you want to create the output but post manually created results. Such unequivocal examples are very useful. I do not understand the explanation "1=1,match found,store it 5>2,store it's position and the element 4>3,store it 0<4,neglect it". Neither "store it" not "neglect it" reveal any details about the wanted result.

Sign in to comment.

Answers (4)

Not by looping, however try
a=[1,2;3,4];
b=[1,5,6;4,0,8;11,12,0];
sza = size( a );
is_greater_equal = ( a >= b(1:sza(1),1:sza(2)) )
it returns
is_greater_equal =
1 0
0 1
and to find the indicies
>> [ixr,ixc]=find(is_greater_equal)
ixr =
1
2
ixc =
1
2

2 Comments

Thanks, this is correct answer but i want to continue the comparison for the whole matrices by looping sine i am comparing two images, that's why i need this, like for the first column it does, now for the second and third column, then next row, then first and second column, so on.
Something like this might do it?
sza = ...
for ii = 1 : ...
for jj = 1 : ...
is_greater_equal = ( a(1:sza(1),1:sza(2)) >= b(ii:sza(1),jj:sza(2)) )
...
end
end

Sign in to comment.

Please explain what you're trying to do, rather than how you want to solve it. Because I'm thinking that normalized cross correlation (with function normxcorr2) will help you but I'm not really sure what you want to do. And don't just say you want to scan a large matrix with a small one, say WHY you want to do that so we know whether to recommend normxcorr2() or blockproc(), or if you really need nested looping.

8 Comments

Basically, i want to compare two different sized matrices of two different images and find a match between the elements of the matrices.The elements which are matched should be stored in another new matrix.
Eg; Big matrix;
[1 2 3 4 5 6;
1 2 3 4 5 6;
1 2 3 4 5 6;
1 2 3 4 5 6]
Small matrix;
[1 2 3;
2 3 4;
3 4 5]
Now comparison should be done of small matrix 3x3 with big matrix 4x6.The 3x3 should be first compared with 3x3 of bigger matrix. Then increment the column and then again compare 3x3 elements with next 3x3 of bigger matrix. Then increment the row and do same process again till all the elements of the bigger matrix are compared with the small matrix.
Can you explain what is the first 3x3 and the second 3x3 in your big matrix
The first 3x3 are the first nine elements of the bigger matrix,second 3x3 means next 9 elements of he matrix with next column when column is incremented .
Try normalized cross correlation - it does exactly that. See this demo where I applied it to a color image to find a small color subimage inside the larger color image:
% Demo to use normxcorr2 to find a template (a white onion)
% in a larger image (of a pile of vegetables)
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 11;
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB color demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'peppers.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
subplot(2, 2, 1);
imshow(rgbImage, []);
axis on;
title('Original Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0, 0, 1, 1]);
% Let's get our template by extracting a small portion of the original image.
templateWidth = 71
templateHeight = 49
smallSubImage = imcrop(rgbImage, [192, 82, templateWidth, templateHeight]);
subplot(2, 2, 2);
imshow(smallSubImage, []);
axis on;
title('Template Image to Search For', 'FontSize', fontSize);
% Ask user which channel to search for a match.
% channelToCorrelate = menu('Correlate which color channel?', 'Red', 'Green', 'Blue');
% It actually finds the same location no matter what channel you pick,
% for this image anyway, so let's just go with red (channel #1).
channelToCorrelate = 1;
correlationOutput = normxcorr2(smallSubImage(:,:,1), rgbImage(:,:, channelToCorrelate));
subplot(2, 2, 3);
imshow(correlationOutput, []);
axis on;
title('Normalized Cross Correlation Output', 'FontSize', fontSize);
% Find out where the normalized cross correlation image is brightest.
[maxCorrValue, maxIndex] = max(abs(correlationOutput(:)));
[yPeak, xPeak] = ind2sub(size(correlationOutput),maxIndex(1))
% Because cross correlation increases the size of the image,
% we need to shift back to find out where it would be in the original image.
corr_offset = [(xPeak-size(smallSubImage,2)) (yPeak-size(smallSubImage,1))]
% Plot it over the original image.
subplot(2, 2, 4); % Re-display image in lower right.
imshow(rgbImage);
axis on; % Show tick marks giving pixels
hold on; % Don't allow rectangle to blow away image.
% Calculate the rectangle for the template box. Rect = [xLeft, yTop, widthInColumns, heightInRows]
boxRect = [corr_offset(1) corr_offset(2) templateWidth, templateHeight]
% Plot the box over the image.
rectangle('position', boxRect, 'edgecolor', 'g', 'linewidth',2);
% Give a caption above the image.
title('Template Image Found in Original Image', 'FontSize', fontSize);
uiwait(helpdlg('Done with demo!'));
Hello Image Analyst,
I have tried this normalised cross correlation method for
template matching and it gives the good result till the template is present in test image
but even when template image is missing from the test image it gives some image results which is the
best correlation coefficient match on the test image. So applying this ncc method how could we point out if template
is not present in the test image..
i am attaching all three images. left one template image. 2. middle test image. 3 right resulted image.TestImage.jpg
AS you can see the visualtisation of tempalte and teest image is different still i got normalised cross correlated image. I need tp say template image is not present in the test image in this scenario..
Please advise some concrete method how to get this done.
Threshold the correlation output image. If there are no pixels above some threshold, then there are no places in your image where your template can be found.
Hello Image Analyst,
Thanks for your kind help. I got the solution for my query..

Sign in to comment.

B=randi(100,9) % the big matrix
[n,m]=size(B);
S=randi(100,3) % the small matrix
out=[];
for id1=1:3:n-3
for id2=1:3:m-3
a=B(id1:id1+2,id2:id2+2);
out=[out;a(a>=S)];
end
end

3 Comments

I am getting error in this code at
line out=[out;a(a>=S)] of 'matrix dimensions must agree'
In your case what are the sizes of your two matrices ?
512x512 and 256x20, basically it can be any two different sized matrices since i am using two different sized images.

Sign in to comment.

B=randi(100,512,512) ; % the big matrix
[n,m]=size(B);
S=randi(100,256,20) % the small matrix
[n1,m1]=size(S);
q1=fix(n/n1);
q2=fix(m/m1);
idxr= [ n1*ones(1,q1) n-n1*q1];
idxc=[m1*ones(1,q2) m-m1*q2];
idxc(~idxc)=[];
idxr(~idxr)=[];
out=[];
ii0=1;
for id1=1:numel(idxr)
ii1=ii0+idxr(id1)-1;
jj0=1;
for id2=1:numel(idxc)
jj1=jj0+idxc(id2)-1;
a=B(ii0:ii1,jj0:jj1);
[nn,mm]=size(a);
b=S(1:nn,1:mm);
out=[out;a(a>=b)];
jj0=jj1+1;
end
ii0=ii1+1;
end

2 Comments

Can you please add comments for each line, as I am beginner in this, and also will be easy to grab the logic.
Thanks
I had comments in my answer. Don't be intimidated by all the fancy stuff I put in there to make a fancy demo. The basic heart of the code is only two lines: one line to call normxcorr2() and one to call max(). The rest is just comments and well-commented things to make a nice gui.

Sign in to comment.

Categories

Find more on Functions in Help Center and File Exchange

Asked:

on 27 Jul 2013

Commented:

on 17 Jul 2019

Community Treasure Hunt

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

Start Hunting!