Linear fit between two sets of independent variables

3 visualizzazioni (ultimi 30 giorni)
i have data set like
X Y
1 1.005388889
2 0.624308036
5 0.622771858
7 0.294506747
9 0.187576608
i want to plot linear fit showing equation and R-square value on the graph, as shown in figure plotted by excel.

Risposte (2)

Jos (10584)
Jos (10584) il 9 Dic 2016
Here are some commands you may find useful. Please take a look at the documentation
X = [...]
Y = [...]
plot(X, Y, 'bo')
[r,p] = corrcoef(X, Y)
p = polyfit(X, Y, 1)
lsline

Star Strider
Star Strider il 9 Dic 2016
Modificato: Star Strider il 9 Dic 2016
It is not as straightforward as it at first seems.
The Code
% X Y
D = [1 1.005388889
2 0.624308036
5 0.622771858
7 0.294506747
9 0.187576608]
X = [D(:,1) ones(size(D(:,1)))]; % Design Matrix
B = X\D(:,2); % Estimate Parameters
Yfit = X*B; % Calcualte Regression Line
Resid = D(:,2) - X*B; % Residuals
Rsq = 1 - sum(Resid.^2)/sum((D(:,2)-mean(D(:,2))).^2); % Calcualte R^2
figure(1)
plot(D(:,1), D(:,2), 'bd', 'MarkerFaceColor','b')
hold on
plot(D(:,1), Yfit)
hold off
axis([0 10 0 1.2])
lbl = sprintf('y = %.3f\\cdotx%+.3f\nR^2 = %.3f', [B' Rsq])
text(6, 0.8,lbl, 'HorizontalAlignment','center')
The Plot
EDIT Typographical error in the ‘lbl’ string. Corrected now.

Community Treasure Hunt

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

Start Hunting!

Translated by