Alternatives to using polyfit and polyval functions??
22 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
%% This Code looks to find wether a quadratic or linear plot gives a lower error for a set of given data.
%% First clearing anything previous data in the script
clc; clear all; close all;
%% Start
%Input Values
d10 = [0.0024; 0.0025; 0.0056; 0.0083; 0.0262; 0.0302; 0.0413; 0.0428];
k = [2.29E-04; 2.28E-04; 2.40E-04; 1.21E-04; 2.58E-03; 4.92E-03; 5.16E-03; 7.00E-03];
% Plot for linear and polynomial
p1 = polyfit(d10, k, 1);
p2 = polyfit(d10, k, 2);
plot(d10, k, 'o');
hold on
plot(d10, polyval(p1, d10), 'b-');
plot(d10, polyval(p2, d10), 'r--');
xlabel('d10 [mm]', 'fontsize', 20);
ylabel('k [mm/sec]','fontsize',20);
xlim([0, 0.05]);
ylim([0, 0.01]);
% Residual Error linear
kfit1 = polyval(p1,d10);
kresid1 = k - kfit1;
SSresid1 = sum(kresid1.^2);
disp(['R Squared Value: ',num2str(SSresid1)]);
% Residual Error quadratic
kfit2 = polyval(p2,d10);
kresid2 = k - kfit2;
SSresid2 = sum(kresid2.^2);
disp(['R Squared Value: ',num2str(SSresid2)]);
if SSresid2 > SSresid1
disp(['Linear has a better SSresid value of: ', num2str(SSresid1)]);
else
disp(['Quadratic has a better SSredid value of: ', num2str(SSresid2)]);
end
This is my code I wrote which finds whether a linear or quadratic plot is better for the given data. Im not looking to use the polyfit and polyval inbuilt functions, can anyone help find an alternative?
1 Commento
Risposte (1)
Jan
il 12 Mar 2021
Modificato: Jan
il 12 Mar 2021
POLYFIT and POLYVAL are simple functions. If your teacher wants you to write them by your own, I assume, that this was a topic in your lessons.
This is some code for the fitting:
% Used: x, y, n = degree of polynomial
V = ones(numel(x), n + 1); % Construct Vandermonde matrix:
for j = n:-1:1
V(:, j) = V(:, j + 1) .* x(:);
end
[Q, R] = qr(V, 0); % Solve least squares problem:
p = transpose(R \ (transpose(Q) * y(:))); % Same as: (V \ y)'
For POLYVAL use the Horner scheme.
Vedere anche
Categorie
Scopri di più su Polynomials in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!