0

我正在寻找以下matlab函数的适当矢量化,以消除for循环并通过多线程提高速度。

size(A)= N-by- N,其中30 <= N <= 60

1e4 <= numIter <= 1e6

function val=permApproxStochSquare(A,numIter)
%// A       ... input square non-negative matrix
%// numIter ... number of interations

N=size(A,1);

alpha=zeros(numIter,1);
for curIter=1:numIter
    U=randn(N,N);
    B=U.*sqrt(A);
    alpha(curIter)=det(B)^2;
end

val=mean(alpha);
end
4

1 回答 1

3

将评论中的讨论总结为稍微提高性能的两个版本的代码:

使用评论中的多个想法,代码需要大约少 1/3 的时间:

N=size(A,1);
%precompute sqrt(A)
sA=sqrt(A);
alpha=zeros(numIter,1);
parfor curIter=1:numIter
    %vectorizing rand did not improve the performance because it increased communitcation when combined with parfor
    U=randn(N,N);
    B=U.*sA;
    alpha(curIter)=det(B);
end
%moved calculation out of the loop to vectorize
val=mean(alpha.^2);

另一种方法是尽可能使用for循环进行矢量化,但对性能的改进很小:

N=size(A,1);
%precompute sqrt(A)
sA=sqrt(A);
alpha=zeros(numIter,1);
%using a for, a vectorized rand outside the loop is faster.
U=randn(N,N,numIter);
B=bsxfun(@times,U,sA);
for curIter=1:numIter
    alpha(curIter)=det(B(:,:,curIter));
end
val=mean(alpha.^2);
于 2015-10-19T14:29:13.857 回答