【问题标题】:Matlab nearest neighbor / track pointsMatlab最近邻/跟踪点
【发布时间】:2015-11-27 05:15:10
【问题描述】:

我有一组 n 复数,它们从时间步 1nsampl 穿过复平面。我想绘制这些数字及其随时间的轨迹(y 轴显示虚部,x 轴显示实部)。这些数字存储在n x nsampl 向量中。然而,在每个时间步中,n 点的顺序是随机的。因此,在每个时间步中,我在最后一个时间步中选择一个点,在当前时间步中找到它的最近邻居,并将其放在与当前点相同的位置。然后我对所有其他n-1 点重复此操作,然后继续下一个时间步骤。这样,上一步中的每个点都与新步骤中的一个点相关联(1:1 关系)。下面给出了我当前的实现和示例。但是我的实现非常慢(10 x 4000 复数需要大约 10 秒)。因为我想增加两者,集合大小n 和时间框架nsampl 这对我来说真的很重要。有没有更聪明的方法来实现这一点以获得一些性能?

n=3 和 nsampl=2 的示例:

%manually create a test vector X
X=zeros(3,2); % zeros(n,nsampl)
X(:,1)=[1+1i; 2+2i; 3+3i];
X(:,2)=[2.1+2i; 5+5i; 1.1+1.1i]; % <-- this is my vector with complex numbers

%vector sort algorithm
for k=2:nsampl
    Xlast=[real(X(:,k-1)) imag(X(:,k-1))];          % create vector with x/y-coords from last time step
    Xcur=[real(X(:,k)) imag(X(:,k))];               % create vector with x/y-coords from current time step
    for i=1:size(X,1) % loop over all n points
        idx = knnsearch(Xcur(i:end,:),Xlast(i,:));  %find nearest neighbor to Xlast(i,:), but only use the points not already associated, thus Xcur(i:end,:) points
        idx = idx + i - 1;
        Xcur([i idx],:) = Xcur([idx i],:);          %sort nearest neighbor to the same position in the vector as it was in the last time step
    end
    X(:,k) = Xcur(:,1)+1i*Xcur(:,2);                %revert x/y coordinates to a complex number
end

结果:

X(:,2)=[1.1+1.1i; 2.1+2i; 5+5i];

谁能帮我加快这段代码的速度?

【问题讨论】:

  • 是否有必要完全复制算法的行为?尤其是步骤 k 中的两个点(比如说第 1 和第 2 点)将第 k+1 步的第 7 个点作为它的邻居,移动它两次。
  • 或者更准确地说我之前的评论,您的描述听起来像“加权二分图的匹配”(最小化权重),并且您的代码执行它的贪婪版本,这接近于最佳解决方案。
  • 我希望我能正确理解您的评论,因为我对二分图一无所知。我想我不必复制完全相同的行为,只要仍然存在 1:1 关系(即X(:,2)=[1.1+1.1i; 2.1+2i; 2.1+2i] 是错误的,因为它为两个不同的祖先找到了两次相同的最近邻居。
  • 好的,让我们简化讨论。以X(:,1)=[1.6,2.6,3.6]X(:,2)=[1,2,3] 为例。据我了解,您的文字已经正确匹配,但是您的算法开始交换。
  • 是的,我的算法会错误地交换它。这不是故意的。

标签: performance matlab nearest-neighbor kdtree


【解决方案1】:

您要解决的问题是组合优化,由the hungarian algorithm(又名munkres)解决。幸运的是,有一个 matlab 的实现available for download. 下载文件并将其放在您的搜索路径或函数旁边。使用它的代码是:

for k=2:size(X,2)
   %build up a cost matrix, here cost is the distance between two points.
   pairwise_distances=abs(bsxfun(@minus,X(:,k-1),X(:,k).'));
   %let the algorithm find the optimal pairing
   permutation=munkres(pairwise_distances);
   %apply it
   X(:,k)=X(permutation,k);
end

【讨论】:

    猜你喜欢
    • 2013-06-08
    • 2014-04-12
    • 2019-07-19
    • 2019-03-14
    • 1970-01-01
    • 2015-03-04
    • 2011-11-10
    • 2013-06-06
    • 2011-12-30
    相关资源
    最近更新 更多