find multiple closest values in a vector at once without "going over" (Matlab) -
let's have following 2 vectors:
a = [1 3 5 7 8 9 10 15 16]; b = [2 4 14]; is there function can use that, every element in b, can find index of closest value element in a without "going over" value i'm searching for? expected output be:
[1 2 7] i have found previous answers address finding closest value, not closest value without exceeding values being searched for.
edited: one-liner:
[~,index] = max(repmat(a,numel(b),1) + 0./bsxfun(@le,a,b'), [], 2) '#% 0./(0 or 1) creates nan mask condition #% isn't met, leaving desired values in matrix #% max ignores nans, conveniently this isn't built-in function pretty simple (link on ideone):
a = [1 3 5 7 8 9 10 15 16]; b = [2 4 14]; c = bsxfun(@minus,b',a) #%' transpose b c(c<0)=nan; #% discard values in greater b [~,ci] = min(c,[],2) #% min ignores nan d = a(ci) #% if want actual values of output:
c = 1 -1 -3 -5 -6 -7 -8 -13 -14 3 1 -1 -3 -4 -5 -6 -11 -12 13 11 9 7 6 5 4 -1 -2 ci = 1 2 7 d = 1 3 10
Comments
Post a Comment