MATLAB: How to compare 2 matrices by their values as well as it’s position.

compareMATLABmatrix

So, i have 2 matrix. It mainly contains x & y coordinates. so it has 2 rows and several columns. Now , I am trying to compare 2 matrix. If a values of those 2 matrix match not only by it's values but also by its position in the 2 matrix match i want to get a value suppose 1 back.
here is an Example
a= [1 2 3 4 5 6
2 3 4 7 8 9]
b=[3 2 1 4 4 7
1 2 3 7 7 6]
Now, the values that matched is [4;7] . but there is 2 [4;7]. now this is where the position part comes to play. I want to just take one. So, if i can also check the posiion and value of the 2 matrix for checking the values i can solve my problem. is there anyway to do that ?

Best Answer

The code below first finds out which positions match for each row separately, and then tests if the matches are in the correct places. If you have more dimensions, you can easily use a loop to run these tests.
a= [1 2 3 4 5 6
2 3 4 7 8 9];
b=[3 2 1 4 4 7
1 2 3 7 7 6];
x_a=a(1,:);
x_b=b(1,:);
y_a=a(2,:);
y_b=b(2,:);
[~,matchpos_x]=ismember(x_a,x_b);
[~,matchpos_y]=ismember(y_a,y_b);
matchpos=find( ...
(1:numel(matchpos_x) == matchpos_x) & ...
(1:numel(matchpos_y) == matchpos_y) );
match=a(:,matchpos)