You are on page 1of 4

%% Fungsi menghitung nilai rata-rata

%% Rata2.m
function y = rata2(x)
% rata2(x) menghasilkan nilai rata-rata dari elemen-elemen vektor (x)
% x harus berupa vektor,
% jika tidak fungsi menghasilkan pesan kesalahan
[m,n] = size(x);
if (~((m==1) | (n==1)) | (m==1 & n ==1))
error('Input harus berupa vektor')
end
N=length(x);
s=sum(x);
y = s/N;

%%Program Regres1.m
clear all;
tic
x = [1.7 1.6 2.8 5.6 1.3 2.2 1.3 1.1 3.2 1.5 5.2 4.6 5.8 3.0];
y = [3.7 3.9 6.7 9.5 3.4 5.6 3.7 2.7 5.5 2.9 10.7 7.6 11.8 4.1];
N = length(x);
xbar = rata2(x);
ybar = rata2(y);
s1=0;
s2=0;
for i=1:N,
s1=s1 + (x(i) - xbar)*(y(i) - ybar);
s2=s2 + (x(i) - xbar)^2;
end;
b = s1/s2;
a = ybar - b*xbar;
xp = 1:0.1:6;
yp = a + b*xp;
figure(1)
plot(x,y,'o',xp,yp,'k','LineWidth',4);
toc

%%Program Regres2.m
clear all;
tic
x = [1.7 1.6 2.8 5.6 1.3 2.2 1.3 1.1 3.2 1.5 5.2 4.6 5.8 3.0];
y = [3.7 3.9 6.7 9.5 3.4 5.6 3.7 2.7 5.5 2.9 10.7 7.6 11.8 4.1];
xbar = rata2(x);
ybar = rata2(y);
x1 = x - xbar;
y1 = y - ybar;
s1 = sum(x1.*y1);
s2 = sum(x1.^2);
b = s1/s2;
a = ybar - b*xbar;
xp = 1:0.1:6;
yp = a + b*xp;
figure(1)
plot(x,y,'o',xp,yp,'k','LineWidth',4);
toc

%%Program Regres3.m
tic
x = [1.7 1.6 2.8 5.6 1.3 2.2 1.3 1.1 3.2 1.5 5.2 4.6 5.8 3.0];
y = [3.7 3.9 6.7 9.5 3.4 5.6 3.7 2.7 5.5 2.9 10.7 7.6 11.8 4.1];
n = length(x);
Sx = 0; Sy = 0; Sxx = 0; Sxy = 0;
for i = 1:n
Sx = Sx + x(i);
Sy = Sy + y(i);
Sxx = Sxx + x(i)*x(i);
Sxy = Sxy + x(i)*y(i);
end

SSXY = Sxy - Sx*Sy/n;


SSX = Sxx - Sx*Sx/n;
xR = Sx/n;
yR = Sy/n;
b1 = SSXY/SSX;
b0 = yR - b1*xR;
yb = b0 + b1*x;
figure(1)
plot(x,y,'ks', x, yb,'r')
toc

function F = fungsi_int(x)
%F = sin(x^2) - 4*cos(x) + 5;
F = x^2 - 4*x + 5;

function G = hasil_int(x)
G = x^3/3 - 2*x^2 + 5*x;

function S = Trapesium(a,b,N)
dx = (b-a)/N;
x=a:dx:b;
S = 0;
figure(1); hold off;
f(1) = fungsi_int(x(1));
for ix = 1:N
S = S + 0.5*dx*(fungsi_int(x(ix)) + ...

fungsi_int(x(ix+1)));
f(ix+1) = fungsi_int(x(ix+1));
plot([x(ix) x(ix+1)],[f(ix) f(ix+1)],'b','LineWidth',3);
hold on;
plot([x(ix) x(ix)], [0 f(ix)],'k--','LineWidth',3);
end;
plot([x(ix+1) x(ix+1)], [0 f(ix+1)],'k--','LineWidth',3);
x1=a:dx/10:b;
for i=1:length(x1)
f1(i)=fungsi_int(x1(i));
end
plot(x1,f1,'r','LineWidth',3)
Int_Eksak = hasil_int(b) - hasil_int(a)
Error = Int_Eksak - S

You might also like