Change dtype data_type fields of numpy array

六眼飞鱼酱① 提交于 2019-12-13 07:18:46

问题


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.


回答1:


Found a workaround!

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




回答2:


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']


来源:https://stackoverflow.com/questions/39384998/change-dtype-data-type-fields-of-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!