如何对二维矩阵的每一行的外积矩阵的评估进行向量化?
How to vectorize the evaluation of outer product matrix for every row of the 2D matrix?
我正在尝试加快评估外积矩阵的过程。我有一个名为 a
的 4*n 矩阵。我想通过公式计算 a
每一行的外积矩阵:
K = a*a';
如果我使用 for
循环编写此过程,则如下所示:
K=zeros(4,4,size(a,2));
for i=1:size(a,2)
K(:,:,i) = a(:,i)*a(:,i)';
end
我找到了另一种方法,使用cellfun
,比以前更慢。
acell = num2cell(a, 1);
b = cellfun(@(x)(x*x'),acell,'UniformOutput',false);
K = reshape(cell2mat(b),4,4,[]);
有什么好的方法可以实现这些过程,比如向量化?
您可以使用 kron
重复矩阵 n 次,因此无需预分配,然后与 a(:).'
执行逐元素乘法,最后重塑以添加第 3 维。
%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 循环方法的可读性,但您应该提高性能。
我正在尝试加快评估外积矩阵的过程。我有一个名为 a
的 4*n 矩阵。我想通过公式计算 a
每一行的外积矩阵:
K = a*a';
如果我使用 for
循环编写此过程,则如下所示:
K=zeros(4,4,size(a,2));
for i=1:size(a,2)
K(:,:,i) = a(:,i)*a(:,i)';
end
我找到了另一种方法,使用cellfun
,比以前更慢。
acell = num2cell(a, 1);
b = cellfun(@(x)(x*x'),acell,'UniformOutput',false);
K = reshape(cell2mat(b),4,4,[]);
有什么好的方法可以实现这些过程,比如向量化?
您可以使用 kron
重复矩阵 n 次,因此无需预分配,然后与 a(:).'
执行逐元素乘法,最后重塑以添加第 3 维。
%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 循环方法的可读性,但您应该提高性能。