Plot Data and Fit Line | Matlab Tutorial in 60 seconds

Опубликовано: 20 Май 2026
на канале: BULLAKI
22,298
1.7k

Plot Data and Fit Line | Matlab Tutorial in 60 seconds

%% Matlab Script

f = figure
hold on
ax = gca

x = -10:1:10
y = x + rand(1,numel(x))+2

h_plot(1) = plot(x, y, '+', 'DisplayName', 'Data')

grid on

p = polyfit(x, y, 1)
h_plot(2) = plot(x, p(1)*x+p(2), 'r', 'DisplayName', 'Fit')

l = legend('show'); l.Location = 'best';
ax.XLabel.String = 'x';
ax.YLabel.String = 'y';

saveas(ax, 'D:\figure.tiff')

%% requires Curve Fitting toolbox
delete(h_plot)
delete(l)

ft = fittype('poly1')
[fitresult, gof] = fit(x', y', ft)

h = plot(fitresult, x, y, 'predobs')
l = legend(h, 'data', 'fit2', 'lower bounds', 'higher bounds', 'Location', 'Best')