mat4py
mat4py copied to clipboard
Numpy arrays are not supported in savemat
As from issue's title. This simple code:
from mat4py import savemat
import numpy as np
data = np.ones((10,1))
savemat('./test.mat', {'data':data})
raises an error. The error arises from numpy arrays not being an instance of Sequence. For the purposes of the library, it doesn't seem that strict Sequence requirements are necessary, so checking for hasattr(array, '__len__') and hasattr(array, '__getitem__')
or isinstance(array, Iterable)
should be enough to parse simple 2d arrays. What do you think @jcbsv @tirkarthi?
Hello @LucaCerina ! If you are still facing this issue, maybe I can help you with it's resolution. Dealing with numpy arrays with mat4py is not an easy thing. In fact, the only way I figured out how to save this is by converting the np.array into lists of lists. (I know it is a workaround but it works until a fix is probably pushed, hopefully 👍 ) Here is a demo : Let's say we have the following matrix (or array) :
data = [1 2 3 4 5
6 7 8 9 0
1 4 5 8 4]
mat4py
is not able to process this data. To save it, we need to convert it into a type list
. Here is the conversion :
converted = [
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 0],
[1, 4, 5, 8, 4]
]
Basically, what I have done is group each row into a list and append each row to a "master" list which contains the whole matrix. When mat4py
saves this list into a mat file, it creates the matrix and within Matlab, it is recognized as it !
Here is a sample code if you want to try:
from mat4py import savemat
matrix = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 0], [1, 4, 5, 8, 4]]
title = "Example saving matrix"
savemat('test.mat', {'title' : title, 'data' : matrix})
To get each row, you can use this statement :
# Assuming that data is type of np.array
row1 = list(data[1,:])
I hope it helps. Have a great day !