function v2 = matchlsq(v1,v2)
%MATCHLSQ Pairs two vectors. Used in RLOCUS subroutines.
%
%   V2S = MATCHLSQ(V1,V2) pairs the entries of the two complex vectors 
%   V1 and V2, returning a permutation V2S of V2 that minimizes the 
%   distance norm(V1-V2,1).
%
%   V2 can also be a matrix, in which case the match is performed with
%   respect to the first column of V2 and all columns of V2 are reordered 
%   consistently with V1.
%
%   See also MATCHPAIRS.

%   Copyright 1986-2020 The MathWorks, Inc. 
n = numel(v1);

% Eliminate Inf entries in V1 and V2 (MATCHPAIRS does not handle Inf)
k1 = find(isfinite(v1)); 
k2 = find(isfinite(v2(:,1))); 

% Compute pairwise distances |V1(i)-V2(j)| and minimize cost (linear
% assignment problem)
cost = abs(v1(k1)-v2(k2,1).');
matchings = matchpairs(cost,1+sum(cost,'all'));

% Permute finite entries and ignore remaining entries (all Inf in one
% of the two vectors)
i1 = k1(matchings(:,1));  j1 = 1:n;  j1(i1) = [];
i2 = k2(matchings(:,2));  j2 = 1:n;  j2(i2) = [];
p([i1;j1(:)]) = [i2;j2(:)];
v2 = v2(p,:);