%% Track Point Positions Over Time
% Use matchpairs to track the movement of several points by minimizing the total changes in distance.
%
% Plot a grid of points at time t=0 in green. At time t=1, some of the points move a small amount in a random direction.

[x,y] = meshgrid(4:6:16);
x0 = x(:)';
y0 = y(:)';
plot(x0,y0,'g*')
hold on
rng default % for reproducibility
x1 = x0 + randn(size(x0));
y1 = y0 + randn(size(y0));
plot(x1,y1,'r*')

%
% Use matchpairs to match the points at t=0 with the points at t=1. To do this, first calculate a cost matrix where C(i,j) is the Euclidean distance from point i to point j.

C = zeros(size(x).^2);
for k = 1:length(y1)
  C(k,:) = vecnorm([x1(k)-x0; y1(k)-y0],2,1)';
end
C

%
% Next, use matchpairs to match the rows and columns in the cost matrix. Specify the cost of unassignment as 1. With such a low cost of unassignment relative to the entries in the cost matrix, it is likely matchpairs will leave some points unmatched.

M = matchpairs(C,1)

% The values M(:,2) correspond to the original points \left(x_0 ,y_0 \right), while the values M(:,1) correspond to the moved points \left(x_1 ,y_1 \right).
%
% Plot the matched pairs of points. The points that moved farther than 2*costUnmatched away from the original point remain unmatched.

xc = [x0(M(:,2)); x1(M(:,1))];
yc = [y0(M(:,2)); y1(M(:,1))];
plot(xc,yc,'-o')

% Copyright 2018 The MathWorks, Inc.