clc; clear; close all;

disp('Ajuste de Curva por Mínimos Quadrados');

xtab = [0.3 2.7 4.5 5.9 7.8];
ytab = [1.8 1.9 3.1 3.9 3.3];

n = length(xtab);
p = 2;

% Somatorio
Sx   = sum(xtab);
Sy   = sum(ytab);
Sxy  = sum(xtab .* ytab);
Sx2  = sum(xtab .^ 2);
Sy2  = sum(ytab .^ 2);

b1 = (Sx * Sy - n * Sxy) / (Sx^2 - n * Sx2)
b0 = (Sy - b1 * Sx) / n

ui = b0 + b1 * xtab;
D  = sum((ytab - ui) .^ 2);

r2     = 1 - D / (Sy2 - (1/n) * Sy^2)
sigma2 = D / (n - p)

u = @(x) b0 + b1 * x;

% Grafico
xgrid = min(xtab) - 0.5 : 0.1 : max(xtab) + 0.5;
figure;
plot(xgrid, u(xgrid), '-', 'LineWidth', 1.5);
hold on;
plot(xtab, ytab, 'ko');
grid on;
xlabel('X');
ylabel('Y');
title('Ajuste de Curva por Mínimos Quadrados');
legend('Reta Ajustada u(x)', 'Dados Experimentais', 'Location', 'northwest');

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: