Issue with writematrix and parfor

11 views (last 30 days)
Raghavasimhan Thirunarayanan
Answered: Edric Ellis on 30 Mar 2020
Hello,
I am currently running a 'parfor' loop with writematrix function in it. The writematrix writes some data to multiple sheets of an .xlsx file (each sheet corresponding to data of one particular run). While doing so, I get the following error:
Unable to write to file 'abc.xls'. Ensure the file is a valid spreadsheet file and is not password protected.
My file is a valid file and is not password protected.
However, if I run a simple 'for' loop, I have no problem and the whole code runs smoothly. My question is two parts 1) How do I use writematrix with parfor such that it does not give the above error? 2) If it is impossible using writematrix, is there any way to save data to a spreadsheet format?
I am desperate for answers :-(
Thanks
  1 Comment
darova
darova on 27 Mar 2020
  • If it is impossible using writematrix, is there any way to save data to a spreadsheet format?

Sign in to comment.

Answers (1)

Edric Ellis
Edric Ellis on 30 Mar 2020
You cannot write to the same file simultaneously from mulitple processes. (This is not a limitation specific to parfor - rather, it's a general limitation). To run in parallel, you must ensure that each worker is writing to a separate file. There are two ways you could do this:
  1. Base the file name on the loop iteration
  2. Base the file name on the "ID" of the task executing on the worker.
Here's a simple (untested) example:
parfor idx = 1:N
% Either: base file name on loop iteration
idxFilename = sprintf('outputFile_%d.xls', idx);
% Or: base file name on tassk ID
t = getCurrentTask();
taskIdFilename = sprintf('outputFile_%d.xls', t.ID);
end

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!