简体   繁体   English

在matlab中沿第3轴复制2d矩阵多次

[英]Duplicating a 2d matrix in matlab along a 3rd axis MANY times

I'm looking to duplication a 784x784 matrix in matlab along a 3rd axis. 我想在matlab中沿第3轴复制784x784矩阵。 The following code seems to work: 以下代码似乎有效:

mat = reshape(repmat(mat, 1,10000),784,784,10000);

Unfortunately, it takes so long to run it's worthless (changing the 10,000s to 1000 makes it take a few minutes, and using 10,000 makes my whole machine freeze up practically). 不幸的是,它需要很长时间才能运行它没有价值(将10,000s改为1000会使它花费几分钟,并且使用10,000会使我的整个机器几乎冻结)。 is there a faster way to do this? 有更快的方法吗?

For reference, I'm looking to use mvnpdf on 10,000 vectors each of length 784, using the same covariance matrix for each. 作为参考,我希望在长度为784的10,000个向量上使用mvnpdf,每个向量使用相同的协方差矩阵。 So my final call looks like 所以我的最终通话看起来像

mvnpdf(X,mu,mat)  

%size(X) = (10000,784), size(mu) = (10000,784), size(mat) = 784,784,10000

If there's a way to do this that's not repeating the covariance matrix 10,000 times, that'd be helpful too. 如果有一种方法可以做到这一点,而不是重复协方差矩阵10,000次,那也是有帮助的。 Thanks! 谢谢!

对于超过2个维度的复制,您需要将复制计数作为数组提供:

out = repmat(mat,[1,1,10000])

Creating a 784x784 matrix 10,000 times isn't going to take advantage of the vectorization in MATLAB, which is going to be more useful for small arrays. 创建一个784x784矩阵10,000次不会利用MATLAB中的矢量化,这对小型阵列更有用。 Avoiding a for loop also won't help too much, given the following: 考虑到以下因素,避免使用for循环也无济于事:

The main speedup you can gain here is by computing the inverse of the covariance matrix once, and then computing the pdf yourself. 你可以在这里获得的主要加速是通过计算协方差矩阵的倒数一次,然后自己计算pdf。 The inverse of sigma takes O(n^3), and you are needlessly doing that 10,000 times. sigma的反转取O(n ^ 3),你不必要地做了10,000次。 (Also, the square root determinant can be precomputed.) For reference, the PDF of the multivariate normal distribution is computed as follows: (此外,可以预先计算平方根行列式。)作为参考,多元正态分布的PDF计算如下:

http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Properties http://en.wikipedia.org/wiki/Multivariate_normal_distribution#Properties

Better to just compute the inverse once, and then compute z = x - mu for each value, then doing z'Sz for each pdf value, and applying a simple function and a constant. 最好只计算一次逆,然后为每个值计算z = x - mu ,然后对每个pdf值执行z'Sz ,并应用简单函数和常量。 But wait! 可是等等! You can vectorize that, too. 你也可以对它进行矢量化。

I don't have MATLAB in front of me, but this is basically what you need to do, and it'll run in an instant. 我没有在我面前使用MATLAB,但这基本上就是你需要做的,而且它会在瞬间运行。

s = inv(sigma);
c = -0.5*log(det(s)) - (k/2)*log(2*pi);
z = x - mu;                   % 10000 x 784 matrix
ans = exp( c - 0.5 .* dot(z*s, z, 2) ); % 10000 x 1 vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM