-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLSA_N_polynomial.m
More file actions
74 lines (63 loc) · 1.79 KB
/
Copy pathLSA_N_polynomial.m
File metadata and controls
74 lines (63 loc) · 1.79 KB
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
65
66
67
68
69
70
71
72
73
74
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Least-Squares-Analysis (LSA) for n-order polynomial fit
%
% Description: generates a random data-set around a polynomial curve with
% preset values and then uses LSA matrix methods to find the coefficients
% of the line of best-fit, and overlays the fit-line to the dataset:
% Equation --> y = b0 + b1*x + b2*x^2 + b3*x^3 + ... + b{n}*x^{n}
%
% Made by: Oscar A. Nieves
% Made in: 2019
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clear all; close all; clc;
%% Generate dataset
x = 0:0.01:2; % x-axis
% Set 'guess' for order of polynomial needed
N_guess = 7;
% Generate N random coefficients for polynomial using a Uniform Distribution
% between the values [a,b]
a = -1;
b = 1;
N = 7; % order of dataset polynomial
coeffs = a + (b - a)*rand(N+1,1);
coeffs_ran = a + (b - a)*rand(N+1,1);
% dataset
S = 0;
for k = 1:N+1
S = S + coeffs(k)*x.^(k-1) + coeffs_ran(k).*randn(size(x));
end
%% Polynomial LSA
n = N_guess;
for k = 1:2*n+1
row_A(k) = sum( x.^(k-1) );
end
for k = 1:n+1
A(k,:) = row_A(k:end-n+k-1);
RHS(k) = sum( S.*x.^(k-1) );
end
% convert b into a column vector
if size(RHS,1) == 1
RHS = RHS.';
end
% Compute coefficient vector
b = A\RHS;
% Fit polynomial to data
y = 0;
for k = 1:n+1
y = y + b(k).*x.^(k-1);
end
% Calculate R^2 coefficient of determination
R2_quad = sum( (y - mean(S)).^2 )./sum( (S - mean(S)).^2 );
disp(['R^2 = ' num2str(R2_quad)]);
% Plots results
figure(1);
set(gcf,'color','w');
scatter(x,S); hold on;
plot(x,y,'r','LineWidth',3); hold off;
legend('Raw Data','Fit-line'); legend boxoff;
legend('Location','northwest');
xlabel('x');
ylabel('y');
axis tight;
set(gca,'FontSize',20);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%