error with curve plotting (polynomial

4 ビュー (過去 30 日間)
ali abbas
ali abbas 2022 年 3 月 18 日
回答済み: Kumar Pallav 2022 年 3 月 21 日
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));
  1 件のコメント
ali abbas
ali abbas 2022 年 3 月 18 日
here is my data

サインインしてコメントする。

回答 (2 件)

Mathieu NOE
Mathieu NOE 2022 年 3 月 21 日
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 2022 年 3 月 21 日
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!

カテゴリ

Help Center および File ExchangeCurve Fitting Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by