user3496585
user3496585

Reputation: 41

compare two vectors with different size in matlab

I have two vectors a , b with different size where size(A) = n & size(b) = m and (n>m), I want to get (n-m) values after comparing as elements in both vectors are closest to others

a = [17    28    41    56    69    84   102   105   123   138   149   160   173   184]              

b = [17    28    42    56    69    83   123   138   149   159   173   185]

what I need is

result = [102 105] 

with matlab

anyone can help me?

Upvotes: 0

Views: 980

Answers (2)

Alan
Alan

Reputation: 3417

At first glance this seems like you could get away with using setdiff if you are only dealing with integer values, however this is actually a bit more complicated.

If I have understood the scenario correctly you are looking to find the D (where D = n-m) values in array a which are the least similar to any element in array b.

The solution given by Luis Mendo will achieve this, however it involved a memory complexity of MxN, which can be prohibitive for larger arrays.

An alternative approach would be the following:

[~, mi] = sort(arrayfun(@(ai) min(abs(b - ai)), a), 'descend');
c = a(mi(1:length(a) - length(b)));

Or, in a more expanded format:

aDiff = nan(1,length(a));
for ai = 1:length(a) %//for each element in A, find...
    aDiff(ai) = min(abs(b - a(ai))); %//the difference from it's closest match in b
end

[~, mi] = sort(aDiff, 'descend'); %//find the elements with the largest difference
d = length(a) - length(b); %//determine how many to return
c = a(mi(1:d)); %//take the D elements with the biggest difference from A

The benefit of these approaches is that it keeps the memory requirements down to 2*length(a) or there abouts, and it can be parallelized over multiple cores if necessary.

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112659

dist = abs(bsxfun(@minus, a(:).', b(:))); %'// distance for all combinations
[~, ind] = sort(min(dist),'descend'); %// compute minimum distance for each
%// element of a, and sort
result = a(ind(1:(numel(a)-numel(b)))); %// pick n-m elements of a with largest
%// minimum distance

Upvotes: 1

Related Questions