我有两个大小相等的向量,例如
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)