简体   繁体   中英

Find the minimum positive difference between elements in vector

A = [1 3 5 8]
B = [1 2 3 4 5 6 7 8]

I would like to create a vector C which returns the rownumber of the element in vector A with the smallest non-negative difference to each element in vector B .

So, given the example above, it should return:

C = [1 2 2 3 3 4 4 4]     

I'm sure there are many ways to do this. Here's one:

A = [1 3 5 8]
B = [1 2 3 4 5 6 7 8]

%create matrices of the values to subtract
[a,b] = meshgrid(A,B);
%subtract
aLessB = a-b;
%make sure we don't use the negative values
aLessB(aLessB < 0) = Inf;
%sort the subtracted matrix
[dum, idx] = sort(aLessB, 2, 'ascend');

idx(:,1) is the solution you are looking for.

An alternative solution:

 D = bsxfun(@minus, A', B);
 D(D < 0) = Inf;
 [~, C] = min(D, [], 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM