Polyfit coeffs weird output
Show older comments
%Importing Data
x1= csvread('C:\Users\User\Desktop\spdctrl.csv',450,0,[450,0,2050,0]);
y= csvread('C:\Users\User\Desktop\spdctrl.csv',450,1,[450,1,2050,1]);
%Curve Fitting and finding R^2
[p,s] = polyfit(x1,y,15);
R2 = 1 - (s.normr/norm(y - mean(y)))^2;
m = polyval(p,x1);
% Plotting Original vs Curve Fit
figure(1)
subplot(2,1,1)
plot(x1,y)
xlabel('X')
ylabel('Original')
subplot(2,1,2)
plot(x1,m)
xlabel('X')
ylabel('Fitted')

%Extracting the Equation of the Curve-Fit
syms x;
sympref('FloatingPointOutput',true);
i=1;
Throttle = 0;
while i<=length(p) %p is 1x16 double
Throttle = Throttle + p(i)*x^(16-i); % (Coeff)*(input)^(16-i) , 16-i because Coeffs are in decreasing order.
i=i+1;
end
disp(['R-squared = ', num2str(R2)])
disp('Model Eq : Throttle = ')
Throttle
%%
Throttle = - 2.3673e-20*x^15 + 2.5403e-17*x^14 - 1.2612e-14*x^13 + 3.8441e-12*x^12 - 8.0455e-10*x^11 + 1.2250e-07*x^10 - 1.4019e-05*x^9 + 0.0012*x^8 - 0.0830*x^7 + 4.3320*x^6 - 173.0548*x^5 + 5.1978e+03*x^4 - 1.1363e+05*x^3 + 1.7069e+06*x^2 - 1.5755e+07*x + 6.7369e+07 (This is the output in the terminal, Notice how Coeffs have very high " 10^ ")
%%
%%converting x from sym to double and plotting the above equation versus the original imported data "x1". This is bsically the same as subplot(2,1,2) above.%%
figure(2)
thr = double(subs(Throttle,x,x1));
plot(x1,thr)

%Testing
%----------------------------
y1 = -2.3673e-20*x1.^15 + 2.5403e-17*x1.^14 - 1.2612e-14*x1.^13 + 3.8441e-12*x1.^12 - 8.0455e-10*x1.^11 + 1.2250e-07*x1.^10 - 1.4019e-05*x1.^9 + 0.0012*x1.^8 - 0.0830*x1.^7 + 4.3320*x1.^6 - 173.0548*x1.^5 + 5.1978e+03*x1.^4 - 1.1363e+05*x1.^3 + 1.7069e+06*x1.^2 - 1.5755e+07*x1 + 6.7369e+07;
figure(3)
plot(x1,y1)

%% I literally just copy pasted the Equation from the terminal output and changed ^ to .^ so i can compute it. then i plotted it versus the same original data x1. This time however i got a very weird result. What is wrong?? if i try to use the equation in other applications, i get the results in figure 3. I need the results in Figure 2 though. Are the coeffs wrong? and if so then why Fig2 and subplot(2,1,2) gave a correct output??
%%

2 Comments
Image Analyst
on 3 Dec 2022
You forgot to attach your data. I can't run your code to try to fix it until you do.
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
Chaos
on 3 Dec 2022
Accepted Answer
More Answers (0)
Categories
Find more on Get Started with Curve Fitting Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!