Finding the slope after drawing a trend/linear fit
1 次查看(过去 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!