title: MATLAB: How to copy a handle object as quickly as possible
body: <p>I'm wondering how I can copy (and maybe delete) handle objects within MATLAB. </p>
  
  <p>I am currently coding a solver for large systems of equations using MATLAB and an add-on called CPLEX. This solver essentially involves creating CPLEX handle objects and then solving them using a solve method as follows:</p>
  
  <pre><code>P = Cplex() %Create a Cplex object
  %Code to specify the Cplex parameters
  P.solve() %solve the Cplex object
  </code></pre>
  
  <p>In the code above, P is a MATLAB Handle Object that belongs to the Cplex() class. It stores a structure of matrices that relate to the factors of their equations. </p>
  
  <p>The main issue that I am running is that I have to "solve" the same CPLEX object numerous times and I would like to do this in parallel, using a parfor loop. Unfortunately, the parfor loop in MATLAB requires transparency, since multiple threads cannot work on the same object. </p>
  
  <p>I've thought of several ways around this: previously, I created and setup the Cplex() file within the parfor loop (this turns out to be slower than a single thread implementation); I also tried saving the object to disk and loading it up within the parfor loop (again too slow). Now I'd like to see if I could copy the object (either within the parfor loop, or outside of it). Unfortunately, however, there is no built-in "copy" function for Cplex objects and I would have to code something like that myself.</p>
  
  <p>Essentially what I would like to do boils down to:</p>
  
  <pre><code>P = Cplex() %creates Cplex object
  %Setup Cplex object
  
  Q = cell(1,n) %create a container for Cplex objects
  
  parfor 1:n
  
  Q{i} = P.copy %create a copy of P and label it as Q{i}
  Q{i}.solve()
  Q{i} = [] %delete Cplex object (for memory purposes /preferable, but not necessary)
  
  end
  </code></pre>