Finding the slope after drawing a trend/linear fit
조회 수: 4 (최근 30일)
이전 댓글 표시
I have an excel data. I want to find the slope after fitting a linear fit on it. In the attached plot, I manually drawn the fit line in black, I need the matlab code for it. So that the program will do it. I've attached my data too.
댓글 수: 0
채택된 답변
Star Strider
2023년 11월 16일
Alternatively —
files = dir('*.xlsx');
T1 = readtable(files.name)
VN = T1.Properties.VariableNames;
T = T1.T;
x = T1.x;
[xmax,idx] = max(x);
idxrng = 1:idx;
DM = [T(idxrng) ones(size(x(idxrng)))]; % Design Matrix
B = DM \ x(idxrng) % Another Option Is 'polyfit'
FitLine = DM * B; % Use 'polyval' With 'polyfit'
xr(1) = 0.004;
yr(1) = [xr 1] * B;
yr(2) = 0.2;
xr(2) = (yr(2)-B(2))/B(1);
figure
plot(T,x)
hold on
plot(T(idxrng), FitLine, '-k', 'LineWidth',3)
plot([1 1]*xr(1), [yr(1) yr(2)], '-r')
plot([xr(1) xr(2)], [1 1]*yr(2), '-r')
hold off
grid
xlabel(VN{1})
ylabel(VN{2})
text(xr(1), yr(2), sprintf('\\uparrow\nSlope = %.2f', B(1)), 'Horiz','left', 'Vert','top')
.
댓글 수: 4
Star Strider
2023년 11월 17일
If you want regression lines for the outset of each variable, this works —
files = dir('*.xlsx');
T1 = readtable(files.name)
VN = T1.Properties.VariableNames;
T = T1.T;
figure
tiledlayout(2,2)
for k = 1:size(T1,2)-1
nexttile
v = T1{:,k+1};
plot(T, v)
grid
title(VN{k+1})
[vmax,idx] = max(v);
idxrng = 1:idx;
DM = [T(idxrng) ones(size(T(idxrng)))]; % Design Matrix
B = DM \ v(idxrng); % Another Option Is 'polyfit'
FitLine = DM * B; % Use 'polyval' With 'polyfit'
hold on
plot(T(idxrng), FitLine, '-k', 'LineWidth',3)
hold off
xlabel(VN{1})
ylabel(VN{k+1})
text(mean(xlim), 0.9*max(ylim), sprintf('Regression Line Slope = %.3f',B(1)), 'Horiz','center', 'Vert','top')
end
The regression lines do not connect the first and first maximum points in all variables because they are fitting all the data between those points. If you want something else, plese be specific.
.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Curve Fitting Toolbox에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!