Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|cite|improve this question
up vote 1 down vote accepted

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;
share|cite|improve this answer
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 :-) – May 29 '12 at 17:35

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.