在Matlab中计算1000个5x5矩阵的协方差 [英] Calculating the covariance of a 1000 5x5 matrices in matlab

查看:181
本文介绍了在Matlab中计算1000个5x5矩阵的协方差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1000个5x5矩阵( Xm ),如下所示:

I have a 1000 5x5 matrices (Xm) like this:

每个$(x_ij) m $是从分布得出的点估计.我想计算每个$ x {ij} $的协方差cov,其中i = 1..n,j = 1..n沿红色箭头方向.

Each $(x_ij)m$ is a point estimate drawn from a distribution. I'd like to calculate the covariance cov of each $x{ij}$, where i=1..n, and j=1..n in the direction of the red arrow.

例如,$ X_m $的方差是var(X,0,3),它给出了5x5的方差矩阵.我可以用相同的方法计算协方差吗?

For example the variance of $X_m$ is `var(X,0,3) which gives a 5x5 matrix of variances. Can I calculate the covariance in the same way?

尝试回答

到目前为止,我已经做到了:

So far I've done this:

for m=1:1000
Xm_new(m,:)=reshape(Xm(:,:,m)',25,1);
end

cov(Xm_new)
spy(Xm_new) gives me this unusual looking sparse matrix:

推荐答案

如果查看cov(命令窗口中的edit cov),您可能会看到为什么它不支持多维数组.它执行输入矩阵xc' * xc的转置和矩阵乘法.这两个操作都不支持多维数组,我猜想是谁编写了该函数的人都决定不对其进行一般化(最好还是与Mathworks联系,但

If you look at cov (edit cov in the command window) you might see why it doesn't support multi-dimensional arrays. It perform a transpose and a matrix multiplication of the input matrices: xc' * xc. Both operations don't support multi-dimensional arrays and I guess whoever wrote the function decided not to do the work to generalize it (it still might be good to contact the Mathworks however and make a feature request).

在您的情况下,如果我们从cov中获取基本代码并做一些假设,则可以编写一个支持3维数组的协方差函数M文件:

In your case, if we take the basic code from cov and make a few assumptions, we can write a covariance function M-file the supports 3-D arrays:

function x = cov3d(x)
% Based on Matlab's cov, version 5.16.4.10

[m,n,p] = size(x);
if m == 1
    x = zeros(n,n,p,class(x));
else
    x = bsxfun(@minus,x,sum(x,1)/m);
    for i = 1:p
        xi = x(:,:,i);
        x(:,:,i) = xi'*xi;
    end
    x = x/(m-1);
end

请注意,此简单代码假定x是沿三维方向堆叠的一系列二维矩阵.归一化标志为0,默认值为cov.可以花很多功夫将其扩展到像var这样的多个维度.在我看来,它比在for循环中调用cov(x(:,:,i))的函数快10倍以上.

Note that this simple code assumes that x is a series of 2-D matrices stacked up along the third dimension. And the normalization flag is 0, the default in cov. It could be exapnded to multiple dimensions like var with a bit of work. In my timings, it's over 10 times faster than a function that calls cov(x(:,:,i)) in a for loop.

是的,我使用了for循环. 更快的方法,但是在这种情况下,for循环将是

Yes, I used a for loop. There may or may not be faster ways to do this, but in this case for loops are going to be faster than most schemes, especially when the size of your array is not known a priori.

这篇关于在Matlab中计算1000个5x5矩阵的协方差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆