function Z = ZernikeFit( S, x, y, numTerms)

[m1, n1] = size( x );
[m2, n2] = size( y );
if( m1 ~= m2 || n1 ~= n2 )
    error( 'x & y are not the same size' );
end

S = S(:);
x = x(:);
y = y(:);

i = find( isfinite( S + x + y ) );
S = S(i);
x = x(i);
y = y(i);

H = zeros( length( S ), numTerms );

for i=1:numTerms
    Z = zeros(1,numTerms);
    Z(i)=1;
    H(:,i)=ZernikeEval(Z,x,y);
end

Z = pinv( H ) * S;
