# How to find nearest two points between two matrices?

I have

```X = (Yt.*sin(W))-(Xt.*cos(W));
Y = (Yt.*cos(W))+(Xt.*sin(W));  % which give the coordinates X and Y.
X_inv = R.*sin(B_involute);
Y_inv = R.*cos(B_involute);     % which give the coordinates X_inv and Y_inv.
```

I need to find the nearest two points between X, Y and X_inv, Y_inv.

lots of thanks from now.

You can compute the pair-wise distances efficiently using pdist2

```D = pdist2( [X(:) Y(:)], [X_inv(:) Y_inv(:)] );
```

Once you have the pairwise distances, it is easy to find the minimal distance

```[md mi] = min(D(:));
```

Conver linear index into pair index

```[idx, inv_idx] = ind2sub( size(D), mi );
```

The result

```fprintf(1, 'Closest points are [%d]: (%f,%f) -> [%d]: (%f,%f)\n',...
idx, X(idx), Y(idx), inv_idx, X_inv(inv_idx), Y_inv(inv_idx) );
```

I'll give you some clues:

1. Use loops to iterate over each X and Y elements in both matrices.
2. Use Euclidean Distance to get distance between current points.
3. Take minimal of all distances that you got.