我有两个大小相等的向量。
A=[2.29 2.56 2.77 2.90 2.05] and
B=[2.34 2.62 2.67 2.44 2.52].
我有兴趣在两个相同大小的向量A & B中找到最接近的值(几乎相等),即在A中的所有元素中,哪个值与B的任何元素最接近?解决方案也应该扩展到任意数量的(等大小)向量。意味着能够用一组相同大小的向量A,B &C找到最近的值。这两个结果的值可以来自两个向量中的任何一个。
为了清晰起见,我不想在一个向量中找到最近的值。上述例子的答案是值2.56和2.52。
发布于 2016-06-12 03:34:30
这适用于可能不同长度的向量的属数。
vectors = {[2.29 2.56 2.77 2.90 2.05] [2.34 2.62 2.67 2.44 2.52] [1 2 3 4]};
% Cell array of data vectors; 3 in this example
s = cellfun(@numel, vectors); % Get vector lengths
v = [vectors{:}]; % Concatenate all vectors into a vector
D = abs(bsxfun(@minus, v, v.')); % Compute distances. This gives a matrix.
% Distances within the same vector will have to be discarded. This will be
% done by replacing those values with NaN, in blocks
bb = arrayfun(@(x) NaN(x), s, 'uniformoutput', false); % Cell array of blocks
B = blkdiag(bb{:}); % NaN mask with those blocks
[~, ind] = min(D(:) + B(:)); % Add that mask. Get arg min in linear index
[ii, jj] = ind2sub(size(D), ind); % Convert to row and column indices
result = v([ii jj]); % Index into concatenated vector
发布于 2016-06-12 02:35:01
作为使用bsxfun的两个向量的起点
%// data
A = [2.29 2.56 2.77 2.90 2.05]
B = [2.34 2.62 2.67 2.44 2.52]
%// distance matrix
dist = abs(bsxfun(@minus,A(:),B(:).'));
%// find row and col indices of minimum
[~,idx] = min(dist(:))
[ii,jj] = ind2sub( [numel(A), numel(B)], idx)
%// output
a = A(ii)
b = B(jj)
现在你可以把它放入一个循环中,等等。
顺便问一下:
dist = abs(bsxfun(@minus,A(:),B(:).'));
相当于更明显的:
dist = pdist2( A(:), B(:) )
但我宁愿选择第一种解决方案,以避免开销。
最后,对多个向量采用完全矢量化的方法:
%// data
data{1} = [2.29 2.56 2.77 2.90 2.05];
data{2} = [2.34 2.62 2.67 2.44 2.52];
data{3} = [2.34 2.62 2.67 2.44 2.52].*2;
data{4} = [2.34 2.62 2.67 2.44 2.52].*4;
%// length of each vector
N = 5;
%// create Filter for distance matrix
nans(1:numel(data)) = {NaN(N)};
mask = blkdiag(nans{:}) + 1;
%// create new input for bsxfun
X = [data{:}];
%// filtered distance matrix
dist = mask.*abs(bsxfun(@minus,X(:),X(:).'));
%// find row and col indices of minimum
[~,idx] = min(dist(:))
[ii,jj] = ind2sub( size(dist), idx)
%// output
a = X(ii)
b = X(jj)
发布于 2016-06-12 06:05:58
正如是一个长注释一样,如果您可以访问统计和机器学习工具箱,那么您可以使用K近邻函数,这些函数有以下优点:
尽管在您的例子中,来自"Luis Mendo“的答案看起来相当不错,但是它不能像工具箱提供的K-最近的邻居函数那样扩展。
更新:一个示例代码
% A and B could have any Dimension, just same number of columns (signal Dimension)
A = rand(1000,4);
B = rand(500,4);
% Use any distance you like, some of them are not supported for KDTreeSearcher,
% and you should use ExhaustiveSearcher
myKnnModel= KDTreeSearcher(A, 'Distance', 'minkowski');
% you can ask for many (K) Nearest Neighbors and you always have access to it for later uses
[Idx, D] = knnsearch(myKnnModel, B, 'K',2);
% and this is answer to your special case
[~, idxA] = min(D(:, 1))
idxB = Idx(idxA)
https://stackoverflow.com/questions/37773140
复制相似问题