How to print to the same file from different PARFOR iterations?
<p>Consider the following pair of functions:</p>

<pre><code>function fileTop
test = fopen('test.txt','w');
fprintf(test,'In function "fileTop"\r\n');
fileMid(test)
fprintf(test,'Back in function "fileTop"');
fclose(test);
end
</code></pre>

<p>and:</p>

<pre><code>function fileMid(fid)
for k = 1:5
    pause(rand)
    fprintf(test,'In "fileMid %d" at %f\r\n',k,now);
end
end
</code></pre>

<p>If you just run <code>fileTop</code> you get a new text file (in case it's the first time) with the following content:</p>

<pre><code>In function "fileTop"
In "fileMid 1" at 736847.920072
In "fileMid 2" at 736847.920073
In "fileMid 3" at 736847.920081
In "fileMid 4" at 736847.920087
In "fileMid 5" at 736847.920096
Back in function "fileTop"
</code></pre>

<p>which is just fine!</p>

<p>Now, try to change the loop in <code>fileMid</code> to <code>parfor</code>, and you get an error:</p>

<blockquote>
  <p>Error using fileMid (line 2)<br>
  Invalid file identifier.  Use fopen to generate a valid file identifier.</p>
</blockquote>

<p>Is there a way to solve this?</p>

<p>BTW, I don't care for the order in which the iterations are printed.</p>