如何对2D矩阵的每一行对外部乘积矩阵的求值向量化? [英] How to vectorize the evaluation of outer product matrix for every row of the 2D matrix?
问题描述
我正在尝试加快评估外部产品矩阵的过程.我有一个名为 a
的4 * n矩阵.我想通过公式
I am trying to speed the process in evaluation the outer product matrix. I have a 4*n matrix named a
. I want to evaluate the outer product matrix for every row of a
, by the formula:
K = a*a';
如果我使用 for
循环对该过程进行编码,则如下所示:
If I code this process using a for
loop, it is as below:
K=zeros(4,4,size(a,2));
for i=1:size(a,2)
K(:,:,i) = a(:,i)*a(:,i)';
end
我发现了另一种使用 cellfun
的方法,该方法比以前更慢.
I have found another method, using cellfun
, which is even slower than before.
acell = num2cell(a, 1);
b = cellfun(@(x)(x*x'),acell,'UniformOutput',false);
K = reshape(cell2mat(b),4,4,[]);
是否有实现这些过程的好方法,例如矢量化?
Is there any good way to implement these process, such as vectorization?
推荐答案
您可以使用 kron
重复n次矩阵,因此无需预先分配,然后使用 a(:).'
,最后重新塑形以添加第3维.
You can use kron
to repeat the matrix n time, so no need to preallocation, then perform an element wise multiplication with a(:).'
, finally reshape to add a 3rd dimension.
%Dummy 2D matrix 4x3
a = [1 4 7
2 5 8
3 6 9
4 7 10]
%Size of the first dimension
n = size(a,1);
%Repeat the matrix n time
p = kron(a,ones(1,n)).*a(:).'
%Reshape to A = 4x4x3
A = reshape(p,n,n,[])
您失去了for循环方法的可读性,但应该提高性能.
You loose the readability of the for loop method but you should increase the performance.
这篇关于如何对2D矩阵的每一行对外部乘积矩阵的求值向量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!