1
votes

Currently I have a parfor loop making calculations on a struct in MATLAB. While my code is a bit long to post, it can be emulated using the following example:

a.test = [1 2 3];
result = [];

parfor i = 1:3
  c = a;
  c.test(2) = round( rand() );

  if c.test(2) == 1
     %# Store c in result
  end
end

disp(result.test) %# Should show [1 1 3]

a (and consequently c) is a very large structure, so storing every iteration is not feasible for me (due to memory constraints).

Ideally I would like to be able to store c straight to a variable that I initialise before the parfor loop. Looking at MATLAB's Example: Using a Custom Reduction Function, I can see it is possible to store a given iteration variable (without having to store every single iteration) yet I do not fully understand their method. I'm baffled by how their function produces 2 separate output variables (seemingly) while the function only defines one output variable.

I am sure this is a very common problem but so far none of my searches have yielded any valid results.

Any help would be much appreciated.

1
I'm a little confused by what you mean here: you want to do parallel iterations and only take the first result that passes some test (presumably canceling the other tasks)? If you're talking about the cummax function in their array, it only does one output (which happens to be a 2-element array). - Danica
Regarding the cummax function I see it now. At first I ignored the A(1) and B(1) as formalities, but I see what it is doing now. You are write though it doesn't apply to me. Cancelling the other tasks isn't important, getting the result out is more important. Jonas below shows an easy way to do this, though. - rbhalla

1 Answers

3
votes

The example you link to is not quite what you want. However, it is possible to store only the "good" results. Here's a simple example:

A=zeros(0,2); %# initialize A with no rows, two columns
parfor i=1:6
   tmp = rand(1); %# create some result
   if tmp > 0.5 %# store only part of the results
      A = [A;[tmp,i]]; %# store also the iteration number, in case it matters
   end
end
>> A

A =

    0.6497    2.0000
    0.5052    4.0000
    0.9993    5.0000