Find the choice of c_0,c_1 and c_2 that gives the best fit of a function of the form f(t) = c_0 + c_1*sin(t) + c_2*cos(t) to the data points (0,0),(1,1), (2,2), (3,3). Substituting: f(0) = c_0 + c_2 = 0 f(1) = c_0 + c_1*sin(1) + c_2*cos(1) = 1 f(2) = c_0 + c_1*sin(2) + c_2*sin(2) = 2 f(3) = c_0 + c_1*sin(3) + c_2*sin(3) = 3 Which gives us a linear system in the unknowns c_0,c_1 and c_2. To compute the matrix of this system in MATLAB and set up a vector for the right-hand side: >> A = [1 0 1; 1 sin(1) cos(1); 1 sin(2) cos(2); 1 sin(3) cos(3)] >> b = [0;1;2;3] [ 1.0000 0 1.0000] [c_0] [0] [ 1.0000 0.8415 0.5403]*[c_1] = [1] [ 1.0000 0.9093 -0.4161] [c_2] [2] [ 1.0000 0.1411 -0.9900] [4] To find the least squares solution we multiply both sides by the transpose of A. (Remember, in MATLAB the transpose of A is A') [4.0000 1.8919 0.1342] [c_0] [ 6.0000] [1.8919 1.5548 -0.0635]*[c_1]=[ 3.0834] [0.1342 -0.0635 2.4452] [c_2] [-3.2620] If the columns of the original matrix A were linearly independent then the 3x3 matrix on the left will be invertible. In MATLAB we can find the inverse of a matrix M using inv(M): Thus the best choice of coefficients c = inv(A'*A)*A'*b giving c0 = 1.5000, c1 = 0.1003, and c2 = -1.4137 We can plot these functions to see how well the trigonometric function f(t) = 1.5 + 0.1003*sin(t) - 1.4137*cos(t) fits the linear function g(t) = t. >> t = 0:0.1:3; % pick a vector of t values between 0 and 3 % the graph of g(t) = t can be obtained using % plot(t,t) Next graph f(t) = 1.5 + 0.1003*sin(t) -1.4137*cos(t) First compute the y-values >> y = 1.5 + 0.1003*sin(t) -1.4137*cos(t); Now plot(t,y) will produce the graph of f on [0,3] We can also include the data points. >> x = [0,1,2,3]; % plot(x,x,'*') will plot the data points as '*' Putting it all together: >> plot(t,t,t,y,x,x,'*')