arrays - 如何找到一个向量中最接近(最近)的值到另一个向量?

标签 arrays matlab vector distance

我有两个大小相等的向量,例如

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。

最佳答案

这适用于一般数量可能不同长度的向量:

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

关于arrays - 如何找到一个向量中最接近(最近)的值到另一个向量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37773140/

相关文章:

javascript - 从 Javascript 中的数组的两个对象计算唯一值

matlab - 图像峰度函数

matlab - 如何在 MATLAB 中编写 GUI?

algorithm - 垂直于 3D 点集合的方向?

c++ - 如何将txt文件读入vector并cout文件?

javascript - 将构造的类名传递给 JQuery

arrays - Powershell 测试数组是否在一行中

python - 在 2D Python 数字字典中插入值

regex - 查找字符串中最短的重复模式

image - 什么是图像矢量?