function run_mnk() % Shows how to use minimal least squares method to fit data. % It loads the file 'mnk.csv'. % % http://strijov.com % Data generation % x = linspace(0,10,200)'; % independent set is generated % y = x + 1.5*sin(x) + randn(size(x,1),1); % dependent set is generated % dlmwrite('mnk.csv', [x,y]); % Load the file D = dlmread('data\mnk.csv'); % Store the data x = D( :, 1:end-1 ); % All columns but the last are independent variables y = D( :,end ); % The last column is independent variable. % The first trial % The regression is y = a x^2 + b x + c A = [x.^2, x, ones(size(x))]; % quadratic function w = inv(A'*A)*(A'*y); % the normal equation ym = w(1) .* x.^2 + w(2).* x + w(3); % the recovered regression % The second trial % The regression is y = a x + b sin(x) + c A = [x, sin(x), ones(size(x))]; % quadratic function w = inv(A'*A)*(A'*y); % the normal equation yr = w(1) .* x + w(2).* sin(x) + w(3); % the recovered regression % Plot the results plot(x,y,'b.'); hold on plot(x,ym,'m-','LineWidth',2); plot(x,yr,'r-','LineWidth',2); hold off title('Linear regression'); legend('sample data','y_{magenta}=w_1x^2+w_2+w_3','y_{red}=w_1x+w_2sin(x)+w_3',2); xlabel('x'); ylabel('y'); return