How to make linear fit?
Ältere Kommentare anzeigen
Hi; I want to plot a linear fit for the graphic in the attached file. And also I want to calculate slope of this linear fit? How can I do this? File is in the attached file.. Thanks a lot.
Antworten (2)
Star Strider
am 22 Jun. 2018
Try this:
I = openfig('test.fig');
Ax = gca;
L1 = findobj(Ax, 'Type','line'); % Find ‘line’ Object
x = L1.XData; % Extract X-Data
y = L1.YData; % Extract Y-Data
XL = [min(x) max(x)]; % Get X-Limits
P = [x(:), ones(size(x(:)))] \ y(:); % Estimate Linear Fit Parameters
LinFit = [XL(:) [1;1]] * P; % Linear Fit
Slope = P(1);
hold on
plot(XL, LinFit, '-r', 'LineWidth',1.5)
hold off
5 Kommentare
Steven Lord
am 22 Jun. 2018
Matt Dickson
am 22 Jun. 2018
Also consider using polyfit to perform the regression and simplify the code, if you want it done in the script.
Star Strider
am 22 Jun. 2018
My code estimates, calculates, and plots a linear fit.
It estimates the parameters as ‘P’, and then calculates a regression line in ‘LinFit’. This is likely more efficient than polyfit and polyval for a simple linear fit.
nancy
am 22 Jun. 2018
Star Strider
am 22 Jun. 2018
Bearbeitet: Star Strider
am 24 Jun. 2018
To use polyfit:
I = openfig('test.fig');
L = findobj(gca, 'Type','line'); % Find ‘line’ Object
x = L(2).XData; % Extract X-Data
y = L(2).YData; % Extract Y-Data
x = x(y > -2); % Remove Outliers
y = y(y > -2); % Remove Outliers
XL = [min(x) max(x)]; % Get X-Limits
P = polyfit(x, y, 1); % Estimate Linear Fit Parameters
LinFit = polyval(P, XL); % Linear Fit
Slope = P(1);
figure
plot(x, y)
hold on
plot(XL, LinFit, '-r', 'LineWidth',1.5)
hold off

EDIT — Added plot image.
Image Analyst
am 23 Jun. 2018
0 Stimmen
See my attached polyfit() demo.

2 Kommentare
nancy
am 24 Jun. 2018
Image Analyst
am 24 Jun. 2018
The demo runs fine. How did you change it? Post your data and code.
Kategorien
Mehr zu Linear and Nonlinear Regression finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!