function pln = fitplane2(r)

% Input r is an nx3 array of vectors stacked vertically.
% Script computes best fit plane to the set of vectors.

% Reduce to 3 equations, 3 unknowns and solve via Cramer's rule.

sr = size(r);
if sr(1) < 3
  fprintf('Cannot form plane\n');
  pln = [1000 1000 1000];
  return;
end;

% Least Squares Fit Plane:
X = cat(1,r(:,1:2),ones(size(r,1),1);
y = r(:,3);

transpose(X\y);

% z = ax + by + c is the equation of the plane.

