It would be also ok for me, if it was possible just to save only the Z(1)...Z(12) in a row-vector. Without the p and q.
Save values from a parfor-loop
4 views (last 30 days)
Show older comments
Hello,
I've got a question regarding my little parfor-example.
Y=rand(100,3)
matlabpool open
parfor p=1:2
for q=1:2
for e=1:3
Z=sum(Y(:,e)+p*q)
end
end
end
matlabpool close
For every combination of p and q there are 3 different values of Z which I would like to save within a matrix. For example in this manner:
1 1 1 1 1 1
1 1 1 2 2 2 . . .
Z(1) Z(2) Z(3) Z(4) Z(5) Z(6)
If it was not a parfor-loop but a simple for-loop, I would try something ike this:
Y=rand(100,3)
z=1
for p=1:2
for q=1:2
for e=1:3
Z=sum(Y(:,e)+p*q)
end
ergebnis(1,z)=p
ergebnis(2,z)=q
ergebnis(3,z)=Z
z=z+1
end
end
But of course that's not possible when working with parfor-loops.
It would be great, if someone helped me out.
Thank's a lot
Domninik
2 Comments
Alex
on 13 Jan 2012
As a recommendation, if you know the size of a matrix beforehand, always initialize it before the loop. Like in your example, ergebnis = zeros(3,12), should be placed before your second loop example. This prevents memory loops that increase in size.
Answers (2)
Alex
on 13 Jan 2012
It looks like parfor sends one variable to each parallel operation, meaning that the variable references must be clear to begin with.
I.e. Z(i) = #, Z(i,j) = #, and Z(i,j,k) = # are valid but Z(i + j) is not valid.
So, that leaves you with two choices, that I know of.
1. Calculate Z as a 2x2x3 matrix
Y=rand(100,3)
Z = zeros([2,2,3]);
matlabpool open
parfor p=1:2
for q=1:2
for e=1:3
Z=sum(Y(:,e)+p*q)
end
end
end
matlabpool close
Now, you have a 2x2x3 matrix that you would need to deference into a vector using tools such as repmat or loops.
2. calculate z as a vector
The other option is to have a single Parallel loop and d3ereference the index's that you want within the loop. An example follows.
Y =rand(10,3);
Z = zeros(1,12);
parfor i = 1:12
l = mod(i,3);
if(l == 0);
l = 3;
end
j = floor( ( i -l) / 6);
k = floor( ( i - l - j) / 3);
Z( i) = sum(Y(:,l)+j*k)
end
matlabpool close
This leaves you with your desired Z vector. However, the inner loop calculations are messier.
0 Comments
dominik ballreich
on 13 Jan 2012
2 Comments
Alex
on 20 Jan 2012
I don't know what the issue is. The following works for me.
Y=rand(100,3)
Z = zeros([2,2,3]);
matlabpool open
parfor p=1:2
for q=1:2
for e=1:3
Z(p,q,e)=sum(Y(:,e)+p*q)
end
end
end
matlabpool close
See Also
Categories
Find more on Parallel for-Loops (parfor) in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!