Finding the slope after drawing a trend/linear fit
4 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Star Strider
le 16 Nov 2023
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 commentaires
Star Strider
le 17 Nov 2023
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.
.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Curve Fitting Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!