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).
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
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.
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.