Linear fit between two sets of independent variables
4 views (last 30 days)
Show older comments
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.
0 Comments
Answers (2)
Jos (10584)
on 9 Dec 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
0 Comments
Star Strider
on 9 Dec 2016
Edited: Star Strider
on 9 Dec 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.
0 Comments
See Also
Categories
Find more on Fit Postprocessing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!