pythonmatlabworkspacemat-filematlab-engine

save() command in matlab engine for python


I am using MATLAB Engine API for Python https://nl.mathworks.com/help/matlab/matlab-engine-for-python.html

I would like to open and save a file.

#import and start the engine
import matlab.engine
eng = matlab.engine.start_matlab()
print('Matlab engine started')
#File of interest
myBadFile='test.mat'
#Synchronize python/matlab working directory
eng.cd(os.getcwd(),nargout=0)
print(eng.pwd())
#Read file contents
VALUES=eng.load(myBadFile,nargout=1)

So far so good. I am actually surprised it worked so smoothly.

I do my stuff on VALUES, then I would like to save it again. If I do

VALUES=eng.save(myBadFile+'.test','VALUES','-v6',nargout=0)

I get:

MatlabExecutionError: Variable 'VALUES' not found.

If I do

VALUES=eng.save(myBadFile+'.test',VALUES,'-v6',nargout=0)

I get

MatlabExecutionError: Argument must contain a character vector.

So how do I save my VALUES which is a valid variable in python environment but it is not seen in matlab apparently?


Solution

  • save operates on the variables contained in MATLAB's workspace, and Python does not share scope with the MATLAB engine instance(s). The matlab.engine instance, however, does have a workspace attribute, defined as follows:

    Python dictionary containing references to MATLAB variables. You can assign data to, and get data from, a MATLAB variable through the workspace. The name of each MATLAB variable you create becomes a key in the workspace dictionary. The keys in workspace must be valid MATLAB identifiers (for example, you cannot use numbers as keys).

    Which you can use to place variables in MATLAB's scope.

    This code, for example:

    import matlab.engine
    eng = matlab.engine.start_matlab()
    x = [1, 2, 3]
    eng.save('test.mat', 'x')
    

    Fails as above:

    Error using save
    Variable 'x' not found.
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\matlabengine.py", line 78, in __call__
        _stderr, feval=True).result()
      File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\futureresult.py", line 68, in result
        return self.__future.result(timeout)
      File "C:\Users\excaza\AppData\Roaming\Python\Python36\site-packages\matlab\engine\fevalfuture.py", line 82, in result
        self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err)
    matlab.engine.MatlabExecutionError: Variable 'x' not found.
    

    But works fine once we copy x into the workspace dict:

    import matlab.engine
    eng = matlab.engine.start_matlab()
    x = [1, 2, 3]
    eng.workspace['x'] = x
    eng.save('test.mat', 'x')