フィルターのクリア

How to obtain r^2 (r squared) value of linear regression plotted using 'lsline'

220 ビュー (過去 30 日間)
Gucci
Gucci 2022 年 3 月 21 日
回答済み: Mathieu NOE 2022 年 3 月 22 日
Hello, what is the syntax to obtain the r-squared (r^2) value if I plotted a best fit linear regression with the 'lsline' function?
  2 件のコメント
Scott MacKenzie
Scott MacKenzie 2022 年 3 月 21 日
You can't get r^2 from lsline. lsline is created from the points. To get r^2, you also need to work with the points. Use the corrcoef function to get r (and then r^2) from the points.
Gucci
Gucci 2022 年 3 月 21 日
Thanks

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

回答 (1 件)

Mathieu NOE
Mathieu NOE 2022 年 3 月 22 日
hello
see suggestion below - even no need of lsline
clc
clearvars
% dummy data
x = (0:100);
a = 1.5;
b = 0.235;
y = a*x +b + 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)
Rsquared = my_Rsquared_coeff(y,f); % correlation coefficient
figure(1);plot(x,y,'*',x,f,'-')
legend('data',eqn)
title(['Data fit , R² = ' 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+" + "+a_hat(i)+"*x";
eqn = eqn+str+a_hat(i)+"*x";
else
% eqn = eqn+" + "+a_hat(i)+"*x^"+(i-1)+" ";
eqn = eqn+str+a_hat(i)+"*x^"+(i-1)+" ";
end
end
eqn = eqn+" ";
end

カテゴリ

Help Center および File ExchangeLinear and Nonlinear Regression についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by