![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/733379/image.png)
How to add correlation factor to the plot?
조회 수: 31 (최근 30일)
이전 댓글 표시
figure(1)
scatter(current, power);
h1 = lsline;
h1.LineWidth = 2;
h1.Color = 'k';
title('Correlation Plot - Current vs Power')
xlabel('Current');
ylabel('Power');
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/733274/image.jpeg)
So I used the above code to plot a correlation plot between two variable. I just need to add the correlation factor. What do I need to do to add that?
The correlation factor is 0.99, I used the corrplot function. However, I made a separate graph and now I want to add the factor to my plot.
댓글 수: 0
채택된 답변
Mathieu NOE
2021년 9월 9일
hello
see my little example below (your code does not show how you get the linear model fit data)
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/733379/image.png)
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(p); % polynomial equation (string)
Rsquared = my_Rsquared_coeff(y,f); % correlation coefficient
figure(3);plot(x,y,'o',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
댓글 수: 4
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Curve Fitting Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!