error with curve plotting (polynomial

1 view (last 30 days)
ali abbas
ali abbas on 18 Mar 2022
Answered: Kumar Pallav on 21 Mar 2022
Hello, i have a data , i imported the data to matlab and draw the plot and from the basic fitting tool i found the polynomial function, however if i coded the polynomiual function it doesnt give me the same graph and i dont know how tol solve this.
I used a cubic function because whenever i use a polynomila degree it tells me it is badly conditioned below is the code i used, i extracted the coef from the basic fitting tool and imge code represents the curve i got from the code
d = @(g)77890-36.98*g+0.007535*g.^2+(1.836*10^(-6))*g.^3-0.06888*g.^4+0.0003544*g.^5;
e = 0:1:2200;
plot(e,d(e));

Answers (2)

Mathieu NOE
Mathieu NOE on 21 Mar 2022
hello
maybe try this code
clc
clearvars
% data
data = readmatrix('DATA.xlsx');
x = data(:,1);
y = data(:,2);
% Fit a polynomial p of degree "degree" to the (x,y) data:
degree = 3;
p = polyfit(x,y,degree);
% Evaluate the fitted polynomial p and plot:
f = polyval(p,x);
eqn = poly_equation(flip(p)); % polynomial equation (string)
Rsquared = my_Rsquared_coeff(y,f); % correlation coefficient
figure(3);plot(x,y,'*',x,f,'-')
legend('data',eqn)
title(['Data fit - R squared = ' num2str(Rsquared)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Rsquared = my_Rsquared_coeff(data,data_fit)
% R2 correlation coefficient computation
% The total sum of squares
sum_of_squares = sum((data-mean(data)).^2);
% The sum of squares of residuals, also called the residual sum of squares:
sum_of_squares_of_residuals = sum((data-data_fit).^2);
% definition of the coefficient of correlation is
Rsquared = 1 - sum_of_squares_of_residuals/sum_of_squares;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function eqn = poly_equation(a_hat)
eqn = " y = "+a_hat(1);
for i = 2:(length(a_hat))
if sign(a_hat(i))>0
str = " + ";
else
str = " ";
end
if i == 2
eqn = eqn+str+a_hat(i)+"*x";
else
eqn = eqn+str+a_hat(i)+"*x^"+(i-1)+" ";
end
end
eqn = eqn+" ";
end

Kumar Pallav
Kumar Pallav on 21 Mar 2022
Hello,
As per my understanding, you expect the same plot using the coefficients extracted from the fitting tool.
I have tried the following code with cubic polynomial:
d = @(g)77890-36.98*g+0.007535*g.^2+(1.836*10^(-6))*g.^3;
e = 0:1:2200;
plot(e,d(e));
and I got the following ouput:
Hope this helps!

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by