0
votes

I want to create excel file outside parfor loop (in the starting of the code) then updating excel file with each loop and finally storing excel file to specific location after loop is complete. But I am getting some errors. with following command :

   matlabpool('open',2);
   pwd='C:\Users\myPC\Desktop';
   fName = fullfile(pwd, 'file.xls');
   %# create Excel COM Server

   Excel = actxserver('Excel.Application');
   Excel.Visible = true;
   %# create new XLS file
   wb = Excel.Workbooks.Add();
   wb.Sheets.Item(1).Activate();%line 10
   offset = 0;

   C1 = {'NAME', 'Max', 'Min','Average'};
   %# calculate cell range to fit matrix (placed below previous one)
   cellRange = xlcalcrange('A1', offset,0, size(C1,1),size(C1,2));
   offset = offset + size(C1,1);
   %# insert matrix in sheet
   Excel.Range(cellRange).Select();
   Excel.Selection.Value =C1;


   parfor i=1:2
   %some code ,  eg :
   MAX =1
   MIN =2
   AVG=3
   name='jpg'
   row2  = { name MAX MIN AVG };
        %# calculate cell range to fit matrix (placed below previous one)
        cellRange = xlcalcrange('A1', offset,0, size(row2,1),size(row2,2));
        offset = offset + size(row2,1);
        Excel.Range(cellRange).Select();  %line32
        Excel.Selection.Value =row2;

   end

   %# parsave XLS file
   wb.SaveAs(fName,1);
   wb.Close(false);

   %# close Excel
   Excel.Quit();
   Excel.delete();
   matlabpool('close');

Above code shows following error: 1. The variable Excel in a parfor cannot be classified., 2. The PARFOR loop cannot run used due to the way variable 'offset' is used., 3. The PARFOR loop cannot run used due to the way variable 'Excel' is used., 4. Valid indices for 'Excel' are restricted in PARFOR loops., 5. Call was rejected by callee.Error in line 10 (wb.Sheets.Item(1).Activate();).

Pls. help to use above code so that I can create excel file which updates inside PARFOR loop and EXCEL file get saved outside PARFOR loop
1

1 Answers

0
votes

It is not safe to write to a file simultaneously from different threads. This is why MATLAB will automatically error when you try to do this sort of thing.

The answer to this problem will be one of the two:

  1. Within the parfor loop, write your outputs to some sort of independent buffers, and then outside the parfor loop write the buffers to the file, serially. Or,
  2. Don't use parfor. Use for instead.

See this: http://blogs.mathworks.com/loren/2009/10/02/using-parfor-loops-getting-up-and-running/ to learn more about the restrictions of the parfor command.