Vectorize and use parfor in a nested loop with five levels
Mostra commenti meno recenti
Hi all,
I'm working on an application that, for now, requires computing a nested loop with five levels. I'm trying to vectorize some parts and to use a parfor for one of the loops. However, I haven't been very successful. Any suggestions would be great. A simplified version of the code looks as follows,
clear all
clc
p1=(1:1:50)';
p2=p1;
np=max(size(p1));
[P1,P2]=meshgrid(p1,p2);
DP=unique(P1-P2);
K=max(size(DP));
ns=1000;
ne=10;
S1=randn(ns,ne);
S2=randn(ns,ne);
S3=randn(ns,ne);
S4=randn(ns,ne);
L1=rand(ns,ne);
L2=rand(ns,ne);
L3=rand(ns,ne);
L4=rand(ns,ne);
a=2;
BR=zeros(np,K,K,K,K);
P=BR;
for i=1:K,
DP1=DP(i);
C1=mean(a*S1*DP1>=0,2);
e1=bsxfun(@times,L1,(1-2*C1));
for j=1:K,
DP2=DP(j);
C2=mean(a*S2*DP2>=0,2);
e2=bsxfun(@times,L2,(1-2*C2));
for l=1:K,
DP3=DP(l);
C3=mean(a*S3*DP3>=0,2);
e3=bsxfun(@times,L3,(1-2*C3));
for m=1:K,
DP4=DP(m);
C4=mean(a*S4*DP4>=0,2);
e4=bsxfun(@times,L4,(1-2*C4));
for pp=1:np,
pr=p2(pp);
dp1=p1-pr;
A=reshape(-bsxfun(@times,a.*C4,dp1'),ns,1,np);
N=bsxfun(@minus,A,e4);
f=exp(N);
PR=f./(1+f);
rev=zeros(ns,ne,np);
for zz=1:np,
rev(:,:,zz)=PR(:,:,zz)*p1(zz);
end
er=reshape(sum(mean(rev,2)),np,1);
[mpr,ind]=max(er);
BR(pp,m,l,j,i)=p1(ind);
P(pp,m,l,j,i)=mpr;
end
end
end
end
end
In this version the problems start when evaluating BR and P in the inner loop. Even though all pp, m, l, j and i are defined, it takes a lot of memory and time to evaluate BR(pp,m,l,j,i)=p1(ind), and I really don't know why. Then, after solving that, I need to improve on vectorizing what might be possible to vectorize, and choose a loop to use the parfor.
Thanks,
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!