Correlation Coefficient in Legend

조회 수: 5 (최근 30일)
Jesus Carreno
Jesus Carreno 2020년 10월 2일
답변: VBBV 2023년 11월 8일
Hi im new to Matlab, Im having trouble knowing how to display my correlation coefficient on my legend, i tried using : text(x, y, sprintf('R = %.2f', R))
but this does not work because it does not include it in the legend. Also how can I make Matlab not round up my correaltion coefficient number? My correlation coefficient number is: 0.999259 but when it shows up in the graph it rounds up to 1
here is my code :
close all;
clc
hT=[400
350
300
250
200
150
100
50 ];
h2=[64
56
46
40
30
22
14
4 ];
plot(hT,h2,'k.','markersize',16)
axis([0 400 0 70]);
%% least square fit
X =[ones(size(hT)),hT];
z=X'*h2;
S=X'*X;
U= chol(S);
w=U'\z;
c=U\w;
q=50:5:400;
fit=c(1)+c(2)*q; % coefficints
hold on
plot(q,fit,'b', 'linewidth',1); % linear least square fit
%%
R= corr(hT,h2)
title('\Deltah_{1-2} VS \Deltah_{1-T}','BackgroundColor','y')
legend('Data', 'Least square fit')
xlabel('\Deltah_{1-T} (mm)')
ylabel('\Deltah_{1-2} (mm)')
grid on

답변 (2개)

Star Strider
Star Strider 2020년 10월 2일
Change the legend call to:
legend('Data', sprintf('Least square fit R = %.2f', R))
.

VBBV
VBBV 2023년 11월 8일
Use the sprintf command in legend function just like the text, and include a higher precision specifier for decimals e.g,. 5 for 5 place decimals to avoid roundoff of numbers in legend appearance
close all;
clc
hT=[400
350
300
250
200
150
100
50 ];
h2=[64
56
46
40
30
22
14
4 ];
plot(hT,h2,'k.','markersize',16)
axis([0 400 0 70]);
%% least square fit
X =[ones(size(hT)),hT];
z=X'*h2;
S=X'*X;
U= chol(S);
w=U'\z;
c=U\w;
q=50:5:400;
fit=c(1)+c(2)*q; % coefficints
hold on
plot(q,fit,'b', 'linewidth',1); % linear least square fit
%%
R= corr(hT,h2);
R = 0.9993
title('\Deltah_{1-2} VS \Deltah_{1-T}','BackgroundColor','y')
legend('Data', sprintf('Least square fit, R = %0.5f',R)) % use the sprintf command with higher precison specifier
xlabel('\Deltah_{1-T} (mm)')
ylabel('\Deltah_{1-2} (mm)')
grid on

카테고리

Help CenterFile Exchange에서 Discrete Data Plots에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by