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 Center および File ExchangeDiscrete Data Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by