0% found this document useful (0 votes)
0 views10 pages

Linear Regression

The document contains MATLAB code for various numerical methods including Linear Regression, Polynomial Regression, Linear Interpolation, Newton-Raphson, Bisection, and False Position methods. Each section includes data initialization, plotting, and calculations to find roots or fit curves to the data. The document also provides predictions based on the fitted models and displays results through graphical representations.

Uploaded by

ironmanthebosss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views10 pages

Linear Regression

The document contains MATLAB code for various numerical methods including Linear Regression, Polynomial Regression, Linear Interpolation, Newton-Raphson, Bisection, and False Position methods. Each section includes data initialization, plotting, and calculations to find roots or fit curves to the data. The document also provides predictions based on the fitted models and displays results through graphical representations.

Uploaded by

ironmanthebosss
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Linear Regression

clear all;
close all;
clc;

x = 1:7;
y = [0.5 2.5 2 4 3.5 6 5.5];

figure(1);
plot(x,y,'ro','LineWidth',1.5);
grid on;
hold on;

n = length(x);

a1 = (n*sum(x.*y) - sum(x)*sum(y)) / (n*sum(x.^2) - sum(x)^2);


a0 = mean(y) - a1*mean(x);

xr = 1:0.01:7;
yr = a1*xr + a0;

figure(1);
plot(xr,yr,'b','LineWidth',1.5);
grid on;
hold on;

Polynomial Regression

clear all;
close all;
clc;

x = 0:5;
y = [2.1 7.7 13.6 27.2 40.9 61.1];

figure(1);
plot(x,y,'ro','LineWidth',1.5);
grid on;
hold on;

n = length(x);

X = [n sum(x) sum(x.^2);
sum(x) sum(x.^2) sum(x.^3);
sum(x.^2) sum(x.^3) sum(x.^4)];

Y = [sum(y) sum(x.*y) sum((x.^2).*y)]';

A = X\Y;
A = A';
a0 = A(1);
a1 = A(2);
a2 = A(3);

xr = 0:0.01:5;
yr = a2*(xr.^2) + a1*xr + a0;

figure(1);
plot(xr,yr,'b','LineWidth',1.5);
grid on;
hold on;

Linear Interpolation

clear all;
close all;
clc;

x = 0:6; % x = 0 1 2 3 4 5 6
y = [0 0.8415 0.9093 0.1411 -0.7568 -0.9589 -0.2794];

n = length(x); % n = 7

figure(1);
plot(x,y,'ro','LineWidth',1.5);
grid on;
hold on;

xs = 0:0.01:6; %xs(315) = 3.14


L = length(xs); % L = 601
ys = zeros(1,L);

for i=1:L

for j=1:(n-1)

if xs(i)>=x(j) && xs(i)<x(j+1)


b = j;
a = j+1;
end
end

%ys(i) = ((xs(i)-x(b))/(x(a)-x(b)))*y(a) - ((xs(i)-x(a))/(x(a)-


x(b)))*y(b);
ys(i) = y(b) + ((y(b)-y(a))/(x(b)-x(a)))*(xs(i)-x(b));

end

figure(1);
plot(xs,ys,'b--');
grid on;
hold on;
xp = 0.79;
tol = 0.001;
ind = find(abs(xs-xp)<=tol);
yp = ys(ind);

display(xp);
display(yp);

figure(1);
plot(xp,yp,'rx','LineWidth',2);
grid on;
hold on;

Newton R
clear all;
close all;
clc;

% Define the function and its derivative


f = @(x) exp(-x) - 1;
df = @(x) -exp(-x);

% Initial guess
x0 = 0;

% Tolerance
tol = 1e-8;

% Iteration counter
iter = 0;

% Initialize current value


x_new = x0;

% Newton-Raphson iteration
while abs(f(x_new)) > tol
x_new = x_new - f(x_new) / df(x_new);
iter = iter + 1;
end

fprintf('Obtained Root using Newton-Raphson Method = %f\n', x_new);


fprintf('Total number of iterations required = %d\n', iter);

Bisection
clear all;
close all;
clc;

f = @(x) x.^5 + x + 1; % Defining the function

x_low = -1; % Lower bracket


x_up = 0; % Upper bracket
tol = 1e-4; % Tolerance
iter = 0; % Iteration counter
% Check if root exists in the interval
if f(x_low) * f(x_up) >= 0
error('No root in the given interval.');
end

% Bisection method loop


while (x_up - x_low)/2 > tol
x_mid = (x_low + x_up) / 2;
if f(x_low) * f(x_mid) < 0
x_up = x_mid; % Root lies between x_low and x_mid
else
x_low = x_mid; % Root lies between x_mid and x_up
end
iter = iter + 1;
end

root_bisection = (x_low + x_up) / 2; % Final root estimate

fprintf('Obtained Root using Bisection Method = %f\n', root_bisection);


fprintf('Total no. of iterations required = %d\n', iter);

False Position
clear all;
close all;
clc;

f = @(x) x^5 + x + 1; % Defining the function


x_low = -1; % Lower bracket
x_up = 0; % Upper bracket
tol = 1e-4; % Tolerance
max_iter = 100; % Maximum allowed iterations
iter = 0; % Iteration counter

% Check if a root is bracketed


if f(x_low) * f(x_up) >= 0
error('No root in the given interval.');
end

while abs(x_up - x_low) > tol


% False position formula
x_fp = x_up - f(x_up) * (x_low - x_up) / (f(x_low) - f(x_up));

if f(x_low) * f(x_fp) < 0


x_up = x_fp; % Root is in [x_low, x_fp]
else
x_low = x_fp; % Root is in [x_fp, x_up]
end

iter = iter + 1;
if iter > max_iter
fprintf('Maximum iterations reached.\n');
break;
end
end

fprintf('\nFalse Position Method Root = %f\n', x_fp);


fprintf('Total number of iterations = %d\n', iter);

exp5prb1
clear all;
close all;
clc;

% Define the function and its derivative


f = @(x) exp(-x) - 1;
df = @(x) -exp(-x);

% Initial guess
x0 = 0;

% Tolerance
tol = 1e-8;

% Iteration counter
iter = 0;

% Initialize current value


x_new = x0;

% Newton-Raphson iteration
while abs(f(x_new)) > tol
x_new = x_new - f(x_new) / df(x_new);
iter = iter + 1;
end

fprintf('Obtained Root using Newton-Raphson Method = %f\n', x_new);


fprintf('Total number of iterations required = %d\n', iter);

exp5prb2a
close all;
clear all;
clc;

% Data
x = [0 4 8 12 16 20];
y = [67 84 98 125 149 185];

% Plot original data


figure(1);
plot(x, y, 'o');
grid on;
hold on;
% Linear fit: y = a1*x + a0
n = length(x);
a1 = (n*sum(x.*y) - sum(x)*sum(y)) / (n*sum(x.^2) - sum(x)^2);
a0 = mean(y) - a1*mean(x);

% Display coefficients
fprintf('Linear Fit: y = %fx + %f\n', a1, a0);

% Plot best-fit line


xr = 0:0.1:40;
yr = a1 * xr + a0;
plot(xr, yr);
title('Linear Fit to Bacterial Growth');
xlabel('Days');
ylabel('Amount (x10^6)');
legend('Data', 'Linear Fit');

% Prediction after 40 days


y40 = a1 * 40 + a0;
fprintf('Predicted bacteria amount after 40 days: %f x10^6\n', y40);

exp5prb2b

close all;
clear all;
clc;

% Given data
x = [0 4 8 12 16 20];
y = [67 84 98 125 149 185];

% Plot original data


figure(1);
plot(x, y, 'o', 'MarkerFaceColor', 'b');
hold on;
grid on;
xlabel('Days');
ylabel('Bacteria Count (×10^6)');
title('Parabolic Fit to Bacterial Growth');

% Construct matrices for 2nd-order polynomial: y = a0 + a1*x + a2*x^2


n = length(x);
X = [n sum(x) sum(x.^2);
sum(x) sum(x.^2) sum(x.^3);
sum(x.^2) sum(x.^3) sum(x.^4)];

Y = [sum(y);
sum(x .* y);
sum((x.^2) .* y)];

% Solve for coefficients


A = X\Y;
a0 = A(1);
a1 = A(2);
a2 = A(3);

% Generate fitted curve


xr = 0:0.1:40; % extended to 40 days for prediction
yr = a0 + a1*xr + a2*(xr.^2);

% Plot the fitted curve


plot(xr, yr, 'r-', 'LineWidth', 2);
legend('Data', '2nd Order Polynomial Fit');

% Predict value at 40 days


y40 = a0 + a1*40 + a2*40^2;
fprintf('Predicted bacteria count at 40 days: %.2f × 10^6\n', y40);

exp5prb3

close all;
clear all;
clc;

x = [0.4 0.8 1.2 1.6 2.0 2.3];


y = [800 975 1500 1950 2900 3600];

figure(1);
plot(x, y, 'o', 'MarkerFaceColor', 'b');
hold on;
grid on;

n = length(x);

% Construct matrices for normal equations (quadratic fit)


X = [n, sum(x), sum(x.^2);
sum(x), sum(x.^2), sum(x.^3);
sum(x.^2), sum(x.^3), sum(x.^4)];

Y = [sum(y); sum(x.*y); sum((x.^2).*y)];

A = X\Y;
A = A';

a0 = A(1);
a1 = A(2);
a2 = A(3);

% Generate fitted values


xr = linspace(min(x), max(x), 100);
yr = a2*(xr.^2) + a1*xr + a0;

plot(xr, yr, 'r-', 'LineWidth', 2);


legend('Data points', 'Quadratic fit');
title('Quadratic Fit to Data');
xlabel('x');
ylabel('y');
exp6prb1
clear all;
close all;
clc;

% Given data
x = [0 1.8 5 6 8.2 9.2 12]; % x values
y = [26 16.415 5.375 3.5 2.015 2.54 8]; % y values

n = length(x);

% Plot original data


figure(1);
plot(x, y, 'ro', 'LineWidth', 1.5);
grid on;
hold on;

% Interpolation range
xs = linspace(min(x), max(x), 500); % Densely sampled x values
ys = zeros(size(xs)); % Preallocate

% Linear interpolation manually


for i = 1:length(xs)
for j = 1:(n-1)
if xs(i) >= x(j) && xs(i) <= x(j+1)
% Linear interpolation formula
ys(i) = y(j) + ((y(j+1) - y(j)) / (x(j+1) - x(j))) * (xs(i) -
x(j));
break;
end
end
end

% Plot interpolated curve


plot(xs, ys, 'b--');

% Interpolation at x = 3.5
x_target = 3.5;
for j = 1:(n-1)
if x_target >= x(j) && x_target <= x(j+1)
y_interp = y(j) + ((y(j+1) - y(j)) / (x(j+1) - x(j))) * (x_target -
x(j));
break;
end
end

% Display result
fprintf('Estimated y at x = %.2f: %.4f\n', x_target, y_interp);

% Plot the interpolated point


plot(x_target, y_interp, 'kx', 'LineWidth', 2);
legend('Data points', 'Interpolated line', 'Estimated point');
xlabel('x');
ylabel('y');
title('Linear Interpolation');
exp5prb2
clear all;
close all;
clc;

% Given data
T = [0 8 16 24 32 40]; % Temperature in Celsius
O2 = [14.621 11.843 9.870 8.418 7.305 6.413]; % Oxygen concentration (mg/L)

n = length(T);

% Plot original data


figure(1);
plot(T, O2, 'ro', 'LineWidth', 1.5);
grid on;
hold on;

% Interpolation range
Ts = 0:0.1:40; % Dense temp range
L = length(Ts);
O2s = zeros(1, L);

% Linear interpolation manually


for i = 1:L
for j = 1:(n-1)
if Ts(i) >= T(j) && Ts(i) <= T(j+1)
% Linear interpolation formula
O2s(i) = O2(j) + ((O2(j+1) - O2(j)) / (T(j+1) - T(j))) * (Ts(i) -
T(j));
break;
end
end
end

% Plot interpolated curve


plot(Ts, O2s, 'b--');

% Estimate at T = 27°C
T_target = 27;
tol = 0.01;
ind = find(abs(Ts - T_target) <= tol);
O2_interp = O2s(ind);

% Display results
fprintf('Estimated Oxygen at T = %.1f°C: %.3f mg/L\n', T_target, O2_interp);

% Exact value and error


O2_exact = 7.986;
error_percent = abs((O2_interp - O2_exact) / O2_exact) * 100;
fprintf('Exact Oxygen: %.3f mg/L\n', O2_exact);
fprintf('Percentage Error: %.2f%%\n', error_percent);

% Mark interpolated point


plot(T_target, O2_interp, 'kx', 'LineWidth', 2);
legend('Data points', 'Interpolated line', 'Estimated point');
xlabel('Temperature (°C)');
ylabel('Oxygen Concentration (mg/L)');
title('Linear Interpolation of Dissolved Oxygen');

exp8prb1
clear all;
close all;
clc;

% Define the function and its derivative


f = @(x) exp(-x) - 1;
df = @(x) -exp(-x);

% Initial guess
x0 = 0;

% Tolerance
tol = 1e-8;

% Iteration counter
iter = 0;

% Initialize current value


x_new = x0;

% Newton-Raphson iteration
while abs(f(x_new)) > tol
x_new = x_new - f(x_new) / df(x_new);
iter = iter + 1;
end

fprintf('Obtained Root using Newton-Raphson Method = %f\n', x_new);


fprintf('Total number of iterations required = %d\n', iter);

You might also like