galah92
galah92

Reputation: 3991

Change dtype data_type fields of numpy array

I have a .mat file which I load using scipy:

from oct2py import octave
import scipy.io as spio
matPath = "path/to/file.mat"
matFile = spio.loadmat(matPath)

I get a numpy array which I want to pass to octave function using oct2py, like that:

aMatStruct = matFile["aMatStruct"]
result = octave.aMatFunction(aMatStruct)

But I get the following error:

oct2py.utils.Oct2PyError: Datatype not supported

It seems it's due to the array dtype, which looks like: [('x', 'O'), ('y', 'O'), ('z', 'O')]

So I thought about changing it to 'S', 'U', or something that's supported.

  1. How can it be done?
  2. I couldn't find a supported dtype in the otc2py documentation. Any help on that?
  3. Is there a way to load the .mat file with another (supported) dtype? I looked here but couldn't find anything useful.

Note that inside aMatFunction it uses aMatStruct like that: x = aMatStruct.x.

Upvotes: 0

Views: 318

Answers (2)

Tasos Papastylianou
Tasos Papastylianou

Reputation: 22245

I was going to suggest converting the resulting array to a valid dictionary but you beat me to it so I won't code it :p

However, the other, simpler solution I was going to suggest is that, since you're only using the struct within octave, you could just load it into its workspace and evaluate directly. i.e. the following works for me:

>>> octave.load("MyFile.mat")
>>> octave.eval("fieldnames(S)")
ans = 
{
  [1,1] = name
  [2,1] = age
}
[u'name', u'age']

EDIT eh screw it, here's the python solution; I'd started it anyway :p

>>> from oct2py import octave
>>> from scipy.io import loadmat
>>> F = loadmat("/home/tasos/Desktop/MyFile.mat")
>>> M = F["S"] # the name of the struct variable I saved in the mat file
>>> M = M[0][0]
>>> D = {M.dtype.names[i]:M[i][0] for i in range(len(M))}
>>> out = octave.fieldnames(D); out
[u'age', u'name']

Upvotes: 0

galah92
galah92

Reputation: 3991

Found a workaround!

I used the following script, which reconstructs python dictionaries from the loaded struct, which oct2py2 in turn interpret as matlab structs.

Upvotes: 0

Related Questions