How to make linear fit?
    7 次查看(过去 30 天)
  
       显示 更早的评论
    
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.
0 个评论
回答(2 个)
  Star Strider
      
      
 2018-6-22
        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 个评论
  Star Strider
      
      
 2018-6-22
				
      编辑:Star Strider
      
      
 2018-6-24
  
			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.
另请参阅
类别
				在 Help Center 和 File Exchange 中查找有关 Linear and Nonlinear Regression 的更多信息
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!





