Trouble fitting a curve using polyfit and polyval

11 Ansichten (letzte 30 Tage)
Deepika Sundresh
Deepika Sundresh am 14 Dez. 2021
Beantwortet: Mathieu NOE am 15 Dez. 2021
I have to fit a straight line to the mean-variance scatterplots of an image channel. I am expected to use polyfit and polyval functions for these. The fitted lines would have the form: noise variance = a*signal mean+b, and I have to find a and b. I tried matlab documentation, but couldn't understand how to proceed. How can I do this?

Antworten (1)

Mathieu NOE
Mathieu NOE am 15 Dez. 2021
hello
see example below :
clc
clearvars
% data
x = (0:100);
b = 1.5;
a = 2.35;
y = a + b*x + 3*randn(size(x));
% Fit a polynomial p of degree "degree" to the (x,y) data:
degree = 1;
p = polyfit(x,y,degree);
% Evaluate the fitted polynomial p and plot:
f = polyval(p,x);
eqn = poly_equation(flip(p)); % polynomial equation (string)
Rsquared1 = my_Rsquared_coeff(y,f); % correlation coefficient
figure(1);plot(x,y,'o',x,f,'-')
legend('data',eqn)
title(['Data fit - R squared = ' num2str(Rsquared1)]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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

Kategorien

Mehr zu Polynomials finden Sie in Help Center und File Exchange

Produkte


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by