[英]vectorization of matlab for-loop
I am looking for proper vectorization of following matlab function to eliminate for-loop and gain speed by multithreading. 我正在寻找适当的以下matlab函数向量化,以消除多线程的for循环并提高速度。
size(A)
= N
-by- N
, where 30 <= N <= 60
size(A)
= N
- 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
To summarize the discussion in the comment to two versions of the code which slightly improve the performance: 总结注释中对两个版本的代码的讨论,这些版本会稍微改善性能:
Using multiple ideas from the comments, the code needs roughly 1/3 less time: 使用注释中的多个想法,代码大约需要减少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);
Another approach, vectorize as far as possible using a for
loop only did small improvemens to the perfrmance: 另一种方法是使用
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.