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

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

问题描述

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

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];

我需要将 xm 映射到 xn,或者换句话说,找出 xn 中哪些坐标最接近 xm.因此,如果我有与这些坐标关联的值,我可以使用这张地图作为索引并将这些值关联起来.

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.

我用for循环写了一个简单的函数:

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

对于上面的例子是返回

xmap =
    1     2     2     3     3     3     8     9    10

它工作正常,但对于长向量(超过 100,000 点)需要一段时间.

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

任何想法如何矢量化此代码?

Any ideas how to vectorize this code?

推荐答案

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

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

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

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

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

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