# Find best offset between 2 sets of numbers

Imagine I have the following vectors:

A = [ 1 5 9 12 16]
B = [     1 4    ]


Now I am looking for an offset, that makes B an subset of A. In this example it would be 8, because B+8 gives numbers that are included in A:

A = [ 1 5 9 12 16] // same as before
B = [     9 12    ] // offset added: 1+8=9 and 4+8=12


Now I have one additional constraint for that: If there is no offset, that can map all numbers of a vector to those of A, than find the number that matches most of the numbers of a vector to those of A:

A = [ 1 5 9 12 16] // same as before
C = [     1 3  4 ]


The solution again would be 8, because this would map 1 and 4 to 9 and 12. 3 gets mapped to 11, which doesn't exist in A, but I have mapped as much numbers as possible to those of A.

I know how to get the best matching offset in my case: For every number b in B, calculate the difference between all numbers in A and b. The (positive) difference that occurs most often is the relevant offset. Now, what's a good way to do this in Matlab? Thanks for any hint!

-

First, you compute all the pairwise differences between the elements of A and B:

diffs = cell2mat(arrayfun(@(x) x-B, A, 'uniformoutput', false));


Then, you need to find the most frequent number in this diffs array. Let's make a histogram first:

n = histc(diffs, min(diffs):max(diffs));


Then, find the most frequent element:

[~,idx] = max(n);
offset = min(diffs)+idx-1;

-
Thank you very much for your work! Yet didn't have the time to integrate it, but looks exactly like what I wanted: A short code doing it :-) – stefan.at.wpf May 29 '12 at 17:35