0

I am working on running a MatLab script (.m) on Python like this (idea from here):

import matlab.engine

eng = matlab.engine.start_matlab()
eng.testing(nargout=0)
test = eng.workspace['M']
print(type(test))
print(test)

This is working, it will print me something like this:

<class 'float'>
252.0

However, on the MatLab side I have something like 30 different variables on its workspace (i.e. 1x1 Figure, 101x1 complex double). Is there any way of "automatic" converting all of the MatLab variables to its respective Python variable?

FFLS
  • 565
  • 1
  • 4
  • 19

1 Answers1

1

The who command in Matlab will return the names of all the variables in the current workspace. You can use it to store the variable names into a variable in Matlab workspace.

eng.evalc('C = who;')

This variable list can be imported into python,

>>> varnames = eng.workspace['C']
>>> varnames
['mvar1', 'mvar2', 'mvar3']

This list can be used in a loop to store their corresponding values into a dict.

mvars = {}
for v in varnames:
    mvars[v] = eng.workspace[v]

This dict can be used as mvars['mvarname'].

rashid
  • 644
  • 7
  • 18