问题
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';
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
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?
回答1:
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,[])
You loose the readability of the for loop method but you should increase the performance.
来源:https://stackoverflow.com/questions/57786211/how-to-vectorize-the-evaluation-of-outer-product-matrix-for-every-row-of-the-2d