function [Q,v] = MinPhi(A,B)
% A and B are m-by-n.
% Q (n-by-n orthogonal) and v (m-by-1) minimize
% norm(A - (B + ev')Q,'fro')
% where e = ones(m,1)

[m,n] = size(A);
e = ones(m,1);

% For a given Q, the v-vector that minimizes
% norm(A - (B + ev')Q,'fro') = norm(AQ' - (B+ev'),'fro')
% = norm((AQ'-B) - ev','fro')
% is
% v = (1/m)(AQ'-B)'*e = (1/m)(Q*sA - sB)
% where

sA = A'*e;
sB = B'*e;
%
% Thus, we want to determine Q so that the Frobenius norm of
%
% A - (B + ev')Q = A - (B + e((1/m)(AQ'-B)'*e)')Q
% = A - BQ - (1/m)ee'(AQ'-B)Q
% = A - BQ - (1/m)ee'(A-BQ)
% = (I - (1/m)ee')(A -BQ)
% = Atilde - Btilde*Q
% where

Atilde = A - (e/m)*sA'; % -2 for (eye(m,m)-e*e')*A
Btilde = B - (e/m)*sB';

% To solve min norm(Atilde - Btilde*Q,'fro') we compute the SVD
[U,S,V] = svd(Atilde'*Btilde);
% and set
Q = V*U';
v = (1/m)*(Q*sA - sB);