From: James on
Hi,
I've been trying to use a parfor on this piece of code but it never executes the if-statements. When the lopp ends, I can't find the net1, net2,... variables in the workspace.

parfor lag =1:max_lags
pad = zeros(N,lag);
%pad the data for shifted correlation
d1 = [pad data_subset];
d2 = [data_subset pad];
nn1 = repmat(rownorm(d1),1,size(d1,2)); %norm of each row
nn2 = repmat(rownorm(d1),1,size(d2,2));
%normalize each row such that its norm equals 1
d1 = d1 ./ nn1;
d2 = d2 ./ nn2;

%this is bad but so far it's the only way I can use
%a parfor
if lag == 1
net6 = triu(abs(d1*d2'));
net8 = triu(abs(d2*d1'));
elseif lag == 2
net5 = triu(abs(d1*d2'));
net9 = triu(abs(d2*d1'));
elseif lag == 3
net4 = triu(abs(d1*d2'));
net10 = triu(abs(d2*d1'));
elseif lag ==4
net3 = triu(abs(d1*d2'));
net11 = triu(abs(d2*d1'));
elseif lag==5
net2 = triu(abs(d1*d2'));
net12 = triu(abs(d2*d1'));
elseif lag==6
net1 = triu(abs(d1*d2'));
net13 = triu(abs(d2*d1'));
end
end %end parfor

The reason I use this if statements is because the parfor wouldn't let stick the results in a 3-D matrix or a cell array.
Any idea why the if statements are not being executed?
Thank you.
James
From: Edric M Ellis on
"James " <jfaghm(a)googlemail.com> writes:

> I've been trying to use a parfor on this piece of code but it never
> executes the if-statements. When the lopp ends, I can't find the net1,
> net2,... variables in the workspace. [...]

Your code essentially comes down to this:

parfor ii=1:2
if ii == 1
x1 = 1;
else
x2 = 2;
end
end

and you observe that you don't get x1 and x2 in your workspace after the
loop ends. This is expected - the statements are executed, but x1 and x2
are not output variables of the loop.

For a variable to be an output from a PARFOR loop, it must either be
"sliced" or a "reduction". Sliced basically means that it's an array
where one dimension is indexed using only the loop variable, and the
other indexing expressions are constant. An example of a reduction is
where a sum is being accumulated in the loop. Like so:

x = zeros(N);
y = 0;
parfor ii=1:N
x(ii, :) = rand(1, N); % x is "sliced"
y = y + max(x(ii,:)); % y is a "reduction"
end

You can slice have sliced cell arrays as outputs from a PARFOR loop,
like so:

x = cell(1, N);
parfor ii=1:N
if ii < 3
x{ii} = rand(3);
else
x{ii} = rand(ii);
end
end

Cheers,

Edric.