how to calculate the variance between columns of matrices

6 views (last 30 days)
Hi I have two matrices a = [NaN 2 3 ; 2 NaN 4 ; 5 NaN 4] and b = [4 2 3 ; 5 NaN 4 ; 7 NaN 9]
What I want to do is create one matrix that shows the variance between each column (between the values located in the same position in each of the two matrices). How to do that? Thanks!!

Answers (3)

Greg Heath
Greg Heath on 22 Sep 2014
Edited: Greg Heath on 22 Sep 2014
>> var(b-a) = [ NaN NaN 8.3333 ]
However, I have no idea what the variance of the difference between two matrices is supposed to represent
Hope this helps
Thank you for formally accepting my answer
Greg
  1 Comment
Matt J
Matt J on 22 Sep 2014
A Commented:
Hi Greg, Thanks for your reply. Ok I'll put in this way: a = [NaN 2 3 ; 2 NaN 4 ; 5 NaN 4] b = [4 2 3 ; 5 NaN 4 ; 7 NaN 9] c= [4 NaN 2 ; 5 8 4 ; 8 NaN 9]
the outup matrix should be [ 0 0 .33; 3 0 0; 2.3 NaN 8.33 ] so the variance should be calculate for each matrix positions considering the values of a, b and c matrixes output matrix format = [ var((a(1,1),b(1,1),c(1,1) var((a(1,2),b(1,2),c(1,1) (...) var((a(2,1),b(2,1),c(2,1) (...) ] Any suggestions? Thanks

Sign in to comment.


Greg Heath
Greg Heath on 25 Sep 2014
No. The output is
>> output = reshape(var([a(:)';b(:)';c(:)']),3,3)
output =
NaN NaN 0.33333
3 NaN 0
2.3333 NaN 8.3333
Hope this helps.
Thank you for formally accepting my answer
Greg

Guillaume
Guillaume on 25 Sep 2014
To calculate the element-wise variance (mean / sum / etc.) of several matrices of the same size, just concatenate them along a new dimension and apply the function along that dimension:
together = cat(3, a, b, c); %concatenate along 3rd dimension
elementwisevar = var(together, 0, 3); %variance along 3rd dimension
%or as a one liner:
elementwisevar = var(cat(3, a, b, c), 0, 3);
By definition, NaN propagates to any calculation you make. It doesn't make much sense to me, but if you want to replace the NaNs with 0:
elementwisevar(isnan(elementwisevar)) = 0;

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!