# error with curve plotting (polynomial

조회 수: 1 (최근 30일)
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 2022년 3월 18일
here is my data

댓글을 달려면 로그인하십시오.

### 답변 (2개)

Mathieu NOE 2022년 3월 21일
hello
maybe try this code clc
clearvars
% data
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
##### 댓글 수: 0이전 댓글 -1개 표시이전 댓글 -1개 숨기기

댓글을 달려면 로그인하십시오.

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 CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

### Community Treasure Hunt

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

Start Hunting!