我有一组坐标列表 (x,y),需要找到列表中每个坐标第一次和最后一次出现的索引。
例如(在我的用例中,我有大约 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 = ???
有没有一种方法也可以获取第一次出现的内容呢?
find(x==y, 1, 'first')
finds the first entry upholding the criterion. Other useful functions might beunique()
- Adriaan