Estimate for Residual variance function calculation
11 views (last 30 days)
Show older comments
Hi, need some help on how to code residual varience, i have the formula and have attached code that i have so far, note slope = B1, intercept = B0
%data
x = normrnd(10, 1, 1, 100);
y = 1 + 2 .* x + normrnd(0, 1, 1, 100);
n = 100;
xBar = mean(x);
yBar = mean(y);
%slope
sxy = cov(x,y) * (n-1);
sxy = sxy(2,1);
sxx = var(x) * (n-1);
slope = sxy/sxx;
%intercept
intercept = yBar - (slope * xBar);
%residual varience
frontThing = 1/n-2;
0 Comments
Answers (1)
Torsten
on 4 Sep 2022
x = normrnd(10, 1, 1, 100);
y = 1 + 2 .* x + normrnd(0, 1, 1, 100);
n = 100;
xBar = mean(x);
yBar = mean(y);
%slope
sxy = cov(x,y) * (n-1);
sxy = sxy(2,1);
sxx = var(x) * (n-1);
slope = sxy/sxx;
%intercept
intercept = yBar - (slope * xBar);
%residual variance
yhat = intercept + slope*x;
residual_variance = (n-1)/(n-2)*var((y-yhat).^2)
2 Comments
Abolfazl Chaman Motlagh
on 4 Sep 2022
the var get the variance of vector itself. by the difinition of formula you should take sum over it !!
which is not the formula is.
i think the correct one is :
residual_variance = (1/(n-2))*sum((y-yhat).^2)
ans if you want to have
, you should take sqrt from above value.
residual_variance = sqrt((1/(n-2))*sum((y-yhat).^2))
Torsten
on 4 Sep 2022
Edited: Torsten
on 4 Sep 2022
You are right - should be
rng('default')
x = normrnd(10, 1, 1, 100);
y = 1 + 2 .* x + normrnd(0, 1, 1, 100);
n = 100;
xBar = mean(x);
yBar = mean(y);
%slope
sxy = cov(x,y) * (n-1);
sxy = sxy(2,1);
sxx = var(x) * (n-1);
slope = sxy/sxx;
%intercept
intercept = yBar - (slope * xBar);
%residual variance
yhat = intercept + slope*x;
residual_variance = 1/(n-2)*(y-yhat)*(y-yhat).'
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!