MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   映射2个向量-帮助向量化 (https://www.labfans.com/bbs/showthread.php?t=23080)

poster 2019-12-10 20:30

映射2个向量-帮助向量化
 
在Matlab中工作,我有2个具有不同长度的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循环编写了一个简单的函数:

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 对于上面的示例是return

xmap = 1 2 2 3 3 3 8 9 10 它可以正常工作,但对于较长的向量(超过100,000点)会花费一些时间。

有什么想法可以向量化此代码吗?



[B]回答:[/B]

哦!另一种选择:由于您要查找两个排序列表之间的紧密对应关系,因此可以使用类似合并的算法同时浏览它们。这应该是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的注释,以上代码并不完全正确!



[url=https://stackoverflow.com/questions/2142826]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 04:59

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.