%% Overdetermined Systems
% This example shows how overdetermined systems are often encountered in various kinds of curve fitting to experimental data.
% A quantity y is measured at several different values of time t to produce the following observations. You can enter the data and view it in a table with the following statements.

t = [0 .3 .8 1.1 1.6 2.3]';
y = [.82 .72 .63 .60 .55 .50]';
B = table(t,y)

%
% Try modeling the data with a decaying exponential function
% $ y(t) =  c_1 + c_2 e^{-t} $.
% The preceding equation says that the vector y should be approximated by a linear combination of two other vectors. One is a constant vector containing all ones and the other is the vector with components exp(-t). The unknown coefficients, c_1 and c_2, can be computed by doing a least-squares fit, which minimizes the sum of the squares of the deviations of the data from the model. There are six equations in two unknowns, represented by a 6-by-2 matrix.

E = [ones(size(t)) exp(-t)]

%
% Use the backslash operator to get the least-squares solution.

c = E\y

%
% In other words, the least-squares fit to the data is
%  y(t) = 0.4760 + 0.3413 e^{-t} .
% The following statements evaluate the model at regularly spaced increments in t, and then plot the result together with the original data:

T = (0:0.1:2.5)';
Y = [ones(size(T)) exp(-T)]*c;
plot(T,Y,'-',t,y,'o')

% E*c is not exactly equal to y, but the difference might well be less than measurement errors in the original data.
% A rectangular matrix A is rank deficient if it does not have linearly independent columns. If A is rank deficient, then the least-squares solution to AX = B is not unique. A\B issues a warning if A is rank deficient and produces a least-squares solution. You can use lsqminnorm to find the solution X that has the minimum norm among all solutions.
% Copyright 2015 The MathWorks, Inc.