convert a Python tuple containing string and numerical data types to Matlab

8 vues (au cours des 30 derniers jours)
Dominique Nguyen
Dominique Nguyen le 8 Mar 2020
Commenté : Stephen23 le 13 Nov 2024
How do I convert the following tuple in python and save it to a "test.mat" file so that I can load and read it in Matlab:
py_tuple = [('cars', 'gm', [['red', 10],['black', 15]]),
('cars', 'ford', ['green',5]),
('cars', 'honda', [])]
  1 commentaire
Stephen23
Stephen23 le 13 Nov 2024
"How do I convert the following tuple in python and save it to a "test.mat" file so that I can load and read it in Matlab:"
Unless you really enjoy fiddling around with files, why not simply access the data directly from MATLAB?:
L = pyrun("x = [('cars', 'gm', [['red', 10],['black', 15]]), ('cars', 'ford', ['green',5]), ('cars', 'honda', [])]","x")
L =
Python list with values: [('cars', 'gm', [['red', 10], ['black', 15]]), ('cars', 'ford', ['green', 5]), ('cars', 'honda', [])] Use string, double or cell function to convert to a MATLAB array.
L{1}
ans =
Python tuple with values: ('cars', 'gm', [['red', 10], ['black', 15]]) Use string, double or cell function to convert to a MATLAB array.
L{2}
ans =
Python tuple with values: ('cars', 'ford', ['green', 5]) Use string, double or cell function to convert to a MATLAB array.
L{3}
ans =
Python tuple with values: ('cars', 'honda', []) Use string, double or cell function to convert to a MATLAB array.
etc.

Connectez-vous pour commenter.

Réponses (2)

Rajani Mishra
Rajani Mishra le 11 Mar 2020
You can either save the data as
1)Python tuple itself in .mat file. For that you have to create a variable of type “py.tuple()” in MATLAB. For more information refer: https://www.mathworks.com/help/matlab/python-data-types.html?s_tid=CRUX_lftnav
Example:
myTuple = py.tuple({'red',10});
myTuple2 = py.tuple({'cars','gm',tuple});
2) Create a cell array with the same elements and store and load it from a mat file. As cell also supports different data types like tuples to be stored. For creating a cell array refer below:

Al Danial
Al Danial le 20 Avr 2022
The SciPy module has a function, savemat, which can write Python variables to MATLAB .m files. Your tuple can be written to test.mat with
from scipy.io import savemat
py_tuple = [('cars', 'gm', [['red', 10],['black', 15]]),
('cars', 'ford', ['green',5]),
('cars', 'honda', [])]
M = { 'py_tuple' : py_tuple }
savemat('test.mat', M)
Loading test.mat in MATLAB gives
>> t = load('test.mat');
>> t.py_tuple
ans =
3×3 cell array
{'cars'} {'gm' } {2×2×21 char }
{'cars'} {'ford' } {2×21 char }
{'cars'} {'honda'} {0×0 double}
Section 7.14 of Python for MATLAB Development covers reading and writing .mat files to/from Python in detail.

Catégories

En savoir plus sur Call Python from MATLAB dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by