How to transform these three nested FOR loops into a PARFOR loop?
1 次查看(过去 30 天)
显示 更早的评论
Hi All,
I am trying to modify the three FOR nested loops below to allow the use of the PARFOR command.
A=sparse(m,n)
for j=1:N
for t1=1:T
for t2=t1:T % yes, t1 not 1, this is not a typo
A(f(j,t1,t2),g(j,t1,t2)) = h(j,t1,t2);
end
end
end
f, g and h are linear functions of j, t1 and t2; N>>T.
Replacing the outer FOR loop by a PARFOR loop obviously doesn't do it since A is not a sliced variable as it is right now because of the indexing.
Is there any way to do this?
Thanks in advance,
--Tanguy
0 个评论
采纳的回答
Matt J
2012-10-26
Similar to Chris', I guess, but perhaps a little more readable/generalizable
A=sparse(m,n);
parfor i=1:n*T*T
[j,t1,t2] = ind2sub([N,T,T], i);
A(f(j,t1,t2),g(j,t1,t2)) = h(j,t1,t2);
end
11 个评论
Matt J
2012-10-29
Yes, a different approach will be required. First though, Accept-click this answer (since you say it covers the 3-loop problem in your original post) and start a new post for your new question.
更多回答(2 个)
Chris A
2012-10-26
编辑:Chris A
2012-10-27
Here is a possible solution:
A=sparse(m,n)
indexes=tril(reshape(1:T*T, T, T));
u1=indexes(indexes>0);
v1=[0:T*T:N*T*T-1];
indexes1=kron(ones(numel(u1),1), v1);
indexes2=kron(u1,ones(1,numel(v1)));
indexes=indexes1+indexes2;
for i=1:numel(indexes),
n=indexes(i),
j=floor((n-1)/(T*T))+1;
t1=mod(floor((n-1)/T),T)+1;
t2=mod(n-1,T)+1;
if (t2 < t1),
error('Incorrect index.');
end
A(f(j,t1,t2),g(j,t1,t2)) = h(j,t1,t2);
end
6 个评论
Chris A
2012-10-28
See if this works.
N = 100; %in reality this number is much larger
T = 24;
K = (T+1)*T - sum([1:T]); %constant I use in the loop
A=sparse(N*T*(T+1)/2,(N-1)*T+T);
indexes=tril(reshape(1:T*T, T, T));
u1=indexes(indexes>0);
v1=(0:T*T:N*T*T-1);
indexes1=kron(ones(numel(u1),1), v1);
indexes2=kron(u1,ones(1,numel(v1)));
indexes=indexes1+indexes2;
B=zeros(numel(indexes),3);
parfor i=1:numel(indexes),
n=indexes(i);
j=floor((n-1)/(T*T))+1;
t1=mod(floor((n-1)/T),T)+1;
t2=mod(n-1,T)+1;
% if (t2 < t1),
% error('Incorrect index.');
% end
rw = (j-1)*tempT+(T+1)*(t1-1)-sum([1:(t1-1)])+t2-t1+1; %f
cl = (j-1)*T+t1; %g
% A(rw, cl) = 1; %h=1 to simplify
B(i,:)=[rw cl 1];
end
A(sub2ind(size(b), B(:,1), B(:,2)))=1;
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!