2
比方說,我有以下2個向量:找到多個最接近值一次沒有「去了」(Matlab的)
a = [1 3 5 7 8 9 10 15 16];
b = [2 4 14];
是否有一個功能,我可以使用,這樣,對於每一個元素b
,我可以在a
中找到最接近該元素的索引,而不會「超過」我正在搜索的值?預期結果將是:
[1 2 7]
我發現地址查找最接近的值以前的答案,但被搜索不不超過值最接近的值。
比方說,我有以下2個向量:找到多個最接近值一次沒有「去了」(Matlab的)
a = [1 3 5 7 8 9 10 15 16];
b = [2 4 14];
是否有一個功能,我可以使用,這樣,對於每一個元素b
,我可以在a
中找到最接近該元素的索引,而不會「超過」我正在搜索的值?預期結果將是:
[1 2 7]
我發現地址查找最接近的值以前的答案,但被搜索不不超過值最接近的值。
編輯:現在有一個班輪:
[~,index] = max(repmat(a,numel(b),1) + 0./bsxfun(@le,a,b'), [], 2)
'#% The 0./(0 or 1) creates a NaN mask where the condition
#% isn't met, leaving only the desired values in the matrix
#% max ignores NaNs, conveniently
這是不是一個內置的功能,但它是非常簡單的(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 the values in a greater than b
[~,ci] = min(c,[],2) #% min ignores nan
d = a(ci) #% if you want the actual values of a
輸出:
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