-
Notifications
You must be signed in to change notification settings - Fork 0
/
MJN_LeastSquaresFit.m
executable file
·64 lines (57 loc) · 2.72 KB
/
MJN_LeastSquaresFit.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
%---------------------------------------------------------------------------------------------%
% FUNCTION NAME AND SPECIFICATION
%
% [LS_Soln,varargout] = MJN_LeastSquaresFit(xData,yData,order)
%---------------------------------------------------------------------------------------------%
% PURPOSE OF THIS FUNCTION:
% Performs a simple least-squared regression on a 1-dimensional dataset (x- and y-values
% given by the user), with a customisable order of fit (linear, quadratic, etc)
%---------------------------------------------------------------------------------------------%
% INPUTS:
% xData : Column of x-axis points
% yData : Column of corresponding y-axis points
% order : 1 for linear, 2 for quadratic, etc
%
% OUTPUTS:
% LS_Soln : Vector of size (1,N_order+1) with coeffs. of the LS fit
% varargout{1}: Overall 'error' metric ('R-squared')
% varargout{2}: Vector of y-values that lie along LS curve (i.e., the
% specific preductions of 'y' for each 'x' values in the
% input data), to allow easy/quick plotting of data return
%---------------------------------------------------------------------------------------------%
% GENERAL USAGE NOTES:
% NOTE 1: T
%---------------------------------------------------------------------------------------------%
% CHANGES TO ADD AT SOME POINT IN THE FUTURE:
% TBC
%---------------------------------------------------------------------------------------------%
% CHANGELOG:
% 2024-02-28: Changed function name and altered output to produce R-squared value as first
% optional output argument
%
% 2018-04-02: Created this function as a quick way to do linear data fit 'by hand'
%---------------------------------------------------------------------------------------------%
% Author: Dr Mike Newton
% Date: July 2024
% Location (local): [Matlab_root]/LIBRARY/MJN_Code_Library/MJN_DSP/
% GitHub location: https://github.com/self-noise/Audio-Acoustics-DSP-Tools
%---------------------------------------------------------------------------------------------%
function [LS_Soln,varargout] = MJN_LeastSquaresFit(xData,yData,N_order)
Npts = length(xData);
H = zeros(Npts,N_order+1);
H(:,1) = ones(Npts,1);
for nOrder = 1:N_order
H(:,nOrder+1) = xData.^nOrder;
end
% The key bit that inverts the matrix and to produce gradient(s) and
% y-intercept for the fit
LS_Soln = (H'*H)\H'*yData;
yData_tilde = H*LS_Soln;
R = sum((yData-yData_tilde).^2); % Residual sum of squares
SumSquares = (length(yData)-1)*var(yData); % Total sum of squares
% R-squared error metric (lies between 0:1)
Rsq = 1 - R/SumSquares;
% Optional outputs
varargout{1} = Rsq;
varargout{2} = yData_tilde;
end