ibezito
ibezito

Reputation: 5822

MATLAB var function returns weird results

I get different results when using MATLAB's var function, in compare to when calculating it based on the variance formula.

My input is:

x = [1,1,1,2];

when I use var function I get:

var(x)

ans =
0.2500

when I calculate the variance by using the variance formula I get:

mean((x-mean(x)).^2)

ans =
0.1875

where the variance formula is defined by

enter image description here

Does anyone knows what is the cause for this behavior?

Upvotes: 0

Views: 165

Answers (2)

Irreducible
Irreducible

Reputation: 899

In the description / help of matlab for the function var it says that the sum is normalized by default with N-1 instead of N that is why you get different results:

x = [1,1,1,2];

mean_x=mean(x);

var1=sum((x-mean_x).^2)/length(x)
var2=sum((x-mean_x).^2)/(length(x)-1)

var1 =

0.1875

var2 =

0.2500

You can find here a discussion about the difference of using N-1 rather than N. Var allows you to choose between both normalization by setting the second parameter to 0 default N-1 or 1 for N

Upvotes: 1

Joel Lee
Joel Lee

Reputation: 1119

Just to add on to the point above

V = var(A,w) specifies a weighting scheme. When w = 0 (default), V is normalized by the number of observations-1. When w = 1, it is normalized by the number of observations. w can also be a weight vector containing nonnegative elements. In this case, the length of w must equal the length of the dimension over which var is operating.

Thus, doing var(x,1) will give you the correct answer

Matlab reference

Upvotes: 1

Related Questions