Estimate for Residual variance function calculation
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;
Answers (1)
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))
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).'
Categories
Find more on Exploration and Visualization in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!