import tables from Matlab struct to matrices in python

I want to import tables from a struct in matlab and to store them in python as matrices.
this is the python code I tried
import scipy.io
import numpy as np
# Load the .mat file
data = scipy.io.loadmat('file.mat')
# Access the struct within the loaded data
my_struct = data['structkey']
# Convert each table to a matrix
table1_matrix = my_struct['table1'][0, 0]['arr']
print(table1_matrix)
this is whatwas printed:
[array([[3707764736],
[ 2],
[ 1],
[ 1],
[ 1],
[ 1]], dtype=uint32)]
I can't understand what is printed and don't know what to do to get the table stored in the struct as matrice in python

Respuestas (1)

You need to careful about the datatype that you are working with.
I assume you are working with uint32, which is an unsigned 32-bit integer. Therefore, you have convert the data structure of the table:
table1_matrix = np.array(my_struct['table1'][0, 0]['arr'], dtype=np.float64)
I hope this helps!

4 comentarios

I receive this error message :
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/mayssa/Desktop/50_PINNs/PINNDev/project1.py", line 8, in <module>
table1_matrix = np.array(my_struct['temperature_rod'][0, 0]['arr'], dtype=np.float64)
ValueError: setting an array element with a sequence.
ProblemSolver
ProblemSolver el 5 de Jul. de 2023
Editada: ProblemSolver el 5 de Jul. de 2023
Could you provide the file.mat, so that I can view what is exact data type of the matlab file.
Plus, you can try 'flatten()' to convert the nested array into a 1-D array, and then use astype(np.datatype), where the datatype should be exactly be the same datatype of the matlab "mat" file.
You can try this way as well:
This is my .mat file and it only stores a 1*1 struct with 8 fields
ProblemSolver
ProblemSolver el 5 de Jul. de 2023
Editada: ProblemSolver el 5 de Jul. de 2023
Try using this then:
import scipy.io
data = scipy.io.loadmat('file.mat');
temperature1 = data['your_field_temperature'] % replace 'm' with the field name that you have such as temperature_r..., the complete name
. % create each variable name
. % another variable and so on
print(temperature1)
This is the output I get.

Iniciar sesión para comentar.

Categorías

Productos

Etiquetas

Preguntada:

el 5 de Jul. de 2023

Editada:

el 5 de Jul. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by