在matlab中比较两个不同大小的向量

时间:2014-06-03 12:47:53

标签: matlab

我有两个不同大小的 a b 向量size(A) = n& size(b) = m和(n> m),我希望在比较后获得(n-m)值,因为两个矢量中的元素最接近其他元素

a = [17    28    41    56    69    84   102   105   123   138   149   160   173   184]              

b = [17    28    42    56    69    83   123   138   149   159   173   185]

我需要的是

result = [102 105] 

用matlab

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

乍一看,如果你只处理整数值,你似乎可以使用setdiff,但这实际上有点复杂。

如果我已正确理解方案,那么您希望在数组D中找到D = n-m(其中a)值与数组{{1}中的任何元素最不相似}}

Luis Mendo提供的解决方案将实现这一点,但它涉及MxN的内存复杂性,这对于更大的阵列来说可能是禁止的。

另一种方法如下:

b

或者,以更加扩展的格式:

[~, mi] = sort(arrayfun(@(ai) min(abs(b - ai)), a), 'descend');
c = a(mi(1:length(a) - length(b)));

这些方法的好处是它可以将内存需求保持在aDiff = nan(1,length(a)); for ai = 1:length(a) %//for each element in A, find... aDiff(ai) = min(abs(b - a(ai))); %//the difference from it's closest match in b end [~, mi] = sort(aDiff, 'descend'); %//find the elements with the largest difference d = length(a) - length(b); %//determine how many to return c = a(mi(1:d)); %//take the D elements with the biggest difference from A 或者那里,并且如果需要,可以在多个内核上并行化。

答案 1 :(得分:1)

dist = abs(bsxfun(@minus, a(:).', b(:))); %'// distance for all combinations
[~, ind] = sort(min(dist),'descend'); %// compute minimum distance for each
%// element of a, and sort
result = a(ind(1:(numel(a)-numel(b)))); %// pick n-m elements of a with largest
%// minimum distance
相关问题