mathworks / matlab-engine-for-python

Other
69 stars 9 forks source link

Arrays of structs should be returned as a list of the struct objects #10

Open LightCC opened 2 years ago

LightCC commented 2 years ago

Currently, using Matlab 2019a and the associated Matlab Engine.

The engine fails to convert arrays of structs, which is a known limitation. However, the equivalent of a vector in Matlab is simply a list in Python, or, for a matrix, a list of lists. Other non-struct items correctly translate this way. The struct arrays should simply pass a list of struct objects to Python (which may need further conversion to be usable).

I worked around this by checking if it is a struct with max(size) greater than 1, and if so, I convert the variable to a cell with the struct2cell property, then pull the object into Python, which pulls it in as a list of the struct objects (or list of lists). The engine should be able to do this directly, rather than having to figure out whether to do a conversion first in the Matlab workspace.

An example of such an object is the output of whos: a = whos in Matlab.

Simulink.BusElement example and different error

Also, the Simulink.BusElement object of a Simulink.Bus will be a vector (though could be size 1). It will pull the multi-dimensional struct array into an object in Python, but the .get property fails, even if accessing the keys. i.e. ml.get(BusElement[0]) fails when BusElement is the matlab object given for the Elements property of a Simulink.Bus after translation into Python. The odd thing here is this fails with a different error. There seems to be a problem with the array indexing either in the struct array object, or the get function, or both.

Note

I just happened across the get and struct2cell properties by chance after a lot of digging from a stray answer for something else. I was pulling my hair out on getting this to work. Better documentation or examples for different types would be very helpful.