Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using struct arrays in parfor

I am having trouble using struct arrays in Matlab's parfor loop. The following code has 2 problems I do not understand:

s=struct('a',{},'b',{});
if matlabpool('size')==0
  matlabpool open local 2
end

for j = 1:2      
  parfor k=1:4
    fprintf('[%d,%d]\n',k,j)
    s(j,k).a = k;
    s(j,k).b = j;
  end
end
matlabpool close
  1. It fails with an error Error using parallel_function (line 589) Insufficient number of outputs from right hand side of equal sign to satisfy assignment.
  2. On output, variable s is a vector, not an array (as it should be, even if the code breaks before finishing).

EDIT the problem is solved if I initialize the struct arrays to the correct size, by:

s=struct('a',cell(2,4),'b',cell(2,4));

However, I would still be happy to get insights about the problem (e.g is it rally a bug, as suggested by Oleg Komarov)

like image 509
Itamar Katz Avatar asked Oct 22 '22 09:10

Itamar Katz


1 Answers

It was originally working fine for me but then I don't know what happens. In general you need to be careful with parfor loops and there are ample documentation on how to align everything. Two different words of advice. First and more importantly, the parfor loop is on the outside loop:

function s = foo
s=struct('a',{},'b',{});

parfor j = 1:2      
  for k=1:4
    fprintf('[%d,%d]\n',k,j)
    s(j,k).a = k;
    s(j,k).b = j;
  end
end

Two, Matlab gets very picky about writing the main exit variable (i.e. the variable contained in the parfor loop which is indexed to the loop, in your case, s). You first want to create a dummy variable that holds all the innerloop information, and then writes to it once at the end of the loops. Example:

function s = khal
s=struct('a',{},'b',{});


parfor j = 1:2 
   dummy=struct('a',{},'b',{});
  for k=1:4
    fprintf('[%d,%d]\n',k,j)
    dummy(k).a = k;
    dummy(k).b = j;
  end
  s(j,:) = dummy;
end

You don't have a problem here, but it can get complicated in other instances

like image 168
Rasman Avatar answered Oct 24 '22 04:10

Rasman