

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


m-file of your completed LS_solver.m (Problem 1-(a))
% --------- function file "LS_solver.m" --------- % % input data: x, y and opt % if opt=1, linear model (y=ax+b) % if opt=2, exponential model (y=aexp(bx)) % if opt=3, logarithmic model (y=a+bln(x)) function [a, b]=LS_solver(x, y, opt) [m1, n1]=size(x); [m2, n2]=size(y); % Size of the input data. xx=linspace(min(x), max(x), 100 ); % xx will be used to plot the fitting curve.
if (m1~= 1 )||(m2~= 1 )||(n1~=n2) % If the input data size is not proper, fprintf('Error: Improper input data.\n'); % error message. elseif (opt== 1 )||(opt== 2 )||(opt== 3 ) % option = 1, 2, 3. figure; plot(x, y, 'o'); % Plot the given data points. hold on; % Ready to draw the next graph. switch opt case 1 % Linear model : y = ax + b fprintf('Linear model\n');
% initialize empty n1x2 matrix % fill it up with 1, since the leftmost % column has to be filled with 1 anyways A = ones(n1, 2 ); for i = 1 :n A(i, 2 ) = x(i); end
% form the augmented matrix for the normal % system of the linear system, and reduce % it to rref to obtain the coefficients % a and b Aug = [A'A A'y']; rref_Aug = rref(Aug); sol = rref_Aug(:, 3 );
% plot the resulting mathematical model a=sol( 2 ); b=sol( 1 ); % Fitting constants a and b. plot(xx, axx+b); % Plot the fitting curve with a and b. title('Linear model (y=ax+b)'); case 2 % Exponential model : y = a*exp(bx) fprintf('Exponential model\n');
% make the substitution Y = ln y to linearlize the % exponential model so that we can apply the same % procedures we applied for the linear fit to % obtain the least squares solution Y = zeros(n2); for i = 1 :n Y(i) = log(y(i)); end
% repeat the same procedure, but this time for
% ln a instead of a, since Y = ln a + bx A = ones(n1, 2 ); for i = 1 :n A(i, 2 ) = x(i); end Aug = [A'A A'Y']; rref_Aug = rref(Aug); sol = rref_Aug(:, 3 );
% plot the resulting mathematical model a=exp(sol( 2 )); b=sol( 1 ); % since sol(2) = ln a plot(xx, aexp(bxx)); title('Exponential model (y=a*exp(bx)');
case 3 % Logarithmic model : y = a + b*lnx fprintf('Logarithmic model\n');
% make the substitution X = ln x X = zeros(n1); for i = 1 :n X(i) = log(x(i)); end
% repeat the same procedure as above A = ones(n1, 2 ); for i = 1 :n A(i, 2 ) = X(i); end Aug = [A'A A'y']; rref_Aug = rref(Aug); sol = rref_Aug(:, 3 );
% plot the resulting mathematical model a=sol( 2 ); b=sol( 1 ); plot(xx, b+alog(xx)); title('Logarithmic model (y=a+bln(xx)');
end hold off; % no more graph.
else % for invalid [opt] fprintf('Error: Improper option value.\n'); % error message. return; % Return the process. end end