我有一个坐标列表 (x,y),我需要找到列表中每个坐标第一次和最后一次出现的索引。
示例(在我的 use-cast 我有 ~30M 坐标):

x = [1 3 7 1 3];
y = [5 1 6 5 1];
first = [1 2 3 1 2];
last  = [4 5 3 4 5];

我使用一个矩阵和一个循环来实现它,它看起来像这样,但它很慢:
x1 = min(x);
y1 = min(y);
x2 = max(x);
y2 = max(y);
tic
Mlast = zeros(y2-y1+1, x2-x1+1);
Mfirst = Mlast;

ind = sub2ind(size(Mlast),y-y1+1, x-x1+1);

for i1=1:length(ind)
    first = Mfirst(ind(i1));

    if first == 0
        first = i1;
    end

    Mlast(ind(i1)) = i1;
    Mfirst(ind(i1)) = first;
end

我试图对整个过程进行矢量化,但我只在 Mlast 上取得了成功:
ind = sub2ind(size(Mlast),y-y1+1, x-x1+1);
t = (1:length(x))';
Mlast(ind) = t;
Mfirst = ???

有没有办法在第一次出现时得到这个?

最佳答案

unique 函数可以做到这一点:

[~, b, c] = unique([x(:) y(:)], 'rows', 'first');
first = b(c).';
[~, b, c] = unique([x(:) y(:)], 'rows', 'last');
last = b(c).';

关于arrays - 使用 MATLAB 在坐标列表中查找每个坐标的第一个和最后一个索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54908926/

10-12 18:32
查看更多