How to transform these three nested FOR loops into a PARFOR loop?
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Matt J
on 26 Oct 2012
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 Comments
Matt J
on 29 Oct 2012
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.
More Answers (2)
Chris A
on 26 Oct 2012
Edited: Chris A
on 27 Oct 2012
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 Comments
Chris A
on 28 Oct 2012
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;
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!