I’m wondering how I can copy (and maybe delete) handle objects within MATLAB.
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 = Cplex() %Create a Cplex object
%Code to specify the Cplex parameters
P.solve() %solve the Cplex object
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.
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.
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.
Essentially what I would like to do boils down to:
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
I don’t have CPLEX and since I cannot replicate your code, please try the following suggestion and let me know if it works (or if you get an error, what the error is).
Try defining
Qoutside of theparforloop asThis should create a cell as you had earlier and you can access it as
Q{i}and should save you some time (because if you’re worried about memory issues that you delete each element after processing, then copying it might involve some time overhead too).