Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the first and last index of each coordinate in a list of coordinates using MATLAB

I have a list of coordinates (x,y) and I need to find the index of the first and last occurrence of each coordinate in the list. Example (in my use-cast I have ~30M coordinates):

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

I implemented it using a Matrix and a loop, it looks like this, but it is slow:

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

I tried to vectorize the whole process, but I only succeed with Mlast:

ind = sub2ind(size(Mlast),y-y1+1, x-x1+1);
t = (1:length(x))';
Mlast(ind) = t;
Mfirst = ???

Is there a way to get this for the first occurrence as well?

like image 625
MiB_Coder Avatar asked Jan 27 '23 16:01

MiB_Coder


1 Answers

The unique function can do that:

[~, b, c] = unique([x(:) y(:)], 'rows', 'first');
first = b(c).';
[~, b, c] = unique([x(:) y(:)], 'rows', 'last');
last = b(c).';
like image 104
Luis Mendo Avatar answered Feb 05 '23 15:02

Luis Mendo