映射2个向量 - 帮助向量化 [英] Mapping 2 vectors - help to vectorize

查看:152
本文介绍了映射2个向量 - 帮助向量化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Matlab中工作我有两个不同长度的x坐标向量。例如:

  xm = [15 20 24 25 26 35 81 84 93]; 
xn = [14 22 26 51 55 59 70 75 89 96];

我需要将xm映射到xn,换句话说,找出xn中的哪个坐标最接近XM。所以如果我有与这些坐标相关联的值,我可以使用这个地图作为索引,并将这些值相关联。



两个向量都被排序,每个向量中都没有重复。



我用for-loop写了一个简单的函数:

  function xmap = vectors_map(xm,xn)
xmap = zeros(size(xm));
for k = 1:numel(xm)
[〜,ind] = min(abs(xm(k)-xn));
xmap(k)= ind(1);
end

以上示例返回

  xmap = 
1 2 2 3 3 3 8 9 10

它可以正常工作,但需要一段时间用长向量(超过100,000点)。



任何想法如何向量化此代码? p>

解决方案

哦!另一个选择:由于您正在寻找两个排序列表之间的紧密对应关系,您可以同时使用它们,使用类似合并的算法。这应该是O(max(length(xm),length(xn))) - ish。

  
match_for_xn =零(长(xn),1);
last_M = 1;
N = 1:length(xn)
%搜索M直到找到匹配项。
for M = last_M:length(xm)
dist_to_curr = abs(xm(M) - xn(N));
dist_to_next = abs(xm(M + 1) - xn(N));

如果dist_to_next> dist_to_curr
match_for_xn(N)= M;
last_M = M;
break
else
continue
end

end%M
end%N
/ pre>

编辑:
看到@ yuk的评论,上面的代码不完全正确!


Working in Matlab I have 2 vectors of x coordinate with different length. For example:

xm = [15 20 24 25 26 35 81 84 93];
xn = [14 22 26 51 55 59 70 75 89 96];

I need to map xm to xn, or in other words to find which coordinates in xn are closest to xm. So if I have values associated with those coordinates, I can use this map as index and correlate those values.

Both vectors are sorted and there are no duplicates in each vector.

I wrote a simple function with for-loop:

function xmap = vectors_map(xm,xn)
xmap = zeros(size(xm));
for k=1:numel(xm)
    [~, ind] = min(abs(xm(k)-xn));
    xmap(k) = ind(1);
end

For the above example is returns

xmap =
    1     2     2     3     3     3     8     9    10

It works ok, but takes a while with long vectors (over 100,000 points).

Any ideas how to vectorize this code?

解决方案

Oh! One other option: since you're looking for close correspondences between two sorted lists, you could go through them both simultaneously, using a merge-like algorithm. This should be O(max(length(xm), length(xn)))-ish.


match_for_xn = zeros(length(xn), 1);
last_M = 1;
for N = 1:length(xn)
  % search through M until we find a match.
  for M = last_M:length(xm)
    dist_to_curr = abs(xm(M) - xn(N));
    dist_to_next = abs(xm(M+1) - xn(N));

    if dist_to_next > dist_to_curr
      match_for_xn(N) = M;
      last_M = M;
      break
    else
      continue
    end

  end % M
end % N

EDIT: See @yuk's comment, the above code is not totally correct!

这篇关于映射2个向量 - 帮助向量化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆