2015-10-19 120 views
0

我正在寻找适当的矢量化matlab函数以消除多线程for循环和增益速度。matlab for-loop矢量化

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 
+0

对于大N,使用'parfor'可能是一种选择。 – Daniel

+0

@Daniel是的parfor是简单而好的解决方案,但我需要的解决方案没有Parallel Computing Toolbox(parfor) – michal

+0

除了parfor外,我只想到在循环外部预先计算'sqrt(A)'。 'parfor'可以在没有Parallel Computing Toolbox的情况下使用,但您没有任何灵活性。 – Bentoy13

回答

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循环,只做小improvemens到perfrmance:

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); 
+1

完全同意...此外,第二种方法会产生大的内存需求。 – michal

+0

GPU呢?可以通过PCT在MATLAB CUDA上有效运行此代码吗? – michal

+0

我没有经验,除了需要并行计算工具箱。 – Daniel