mgiordi
mgiordi

Reputation: 153

Variance of elements in matrices (element-by-element) in MATLAB

I am trying to compute the variance of elements which are organised in matrices (in MATLAB). As an example, let's be A and B two matrices 2x2.

enter image description here

My goal is to find the matrix V (2x2 as well), being the variance of each element of A and each element of B, that is:

enter image description here

Can somebody help me on this?

Upvotes: 1

Views: 842

Answers (1)

Dev-iL
Dev-iL

Reputation: 24169

This is a very simple use case of the var function:

A = [1 2;
     3 4];

B = [5 6;
     7 8];

V0 = var(cat(3,A,B),0,3);   
V1 = var(cat(3,A,B),1,3);

This results in:

V0 =

     8     8
     8     8

V1 =

     4     4
     4     4

What happens is that you concatenate your matrices along some unused dimension and then compute the variance along that dimensions.

NOTE: The example of 2 matrices is not very meaningful, but I'm assuming your actual dataset is larger, in which case you could use this method.

Upvotes: 7

Related Questions