我需要用 Python 对 MATLAB 数据进行一些阐述。
数据在 Matlab 中存储为 double 组。当我检索它时,尽管有说明 here当 Python 处理时,Matlab 中的 double
数据类型会转换为 float
数据类型,我收到此错误:
TypeError: unorderable types: double() < float()
我想做的是这个
import matlab.engine
eng=matlab.engine.connect_matlab()
x = eng.workspace['MyData']
x = x[len(x)-1]
if x < 0.01:
#do stuff
如何将数组中存储的 double
数字转换为 float
以便我可以将其与其他 Python 变量一起使用?
最佳答案
在 Matlab 中将 double 转换为 float 就像调用 single function 一样简单:
A = rand(10);
whos A;
B = single(A);
whos B;
根据控制台输出:
Name Size Bytes Class Attributes
A 10x10 800 double
Name Size Bytes Class Attributes
B 10x10 400 single
请注意精度损失,因为您要将 64 位数值转换为 32 位数值。
编辑
由于您无法操作 Matlab 数据,为了实现此目的,我建议您使用 Numpy (请参阅此函数,以防万一: https://docs.scipy.org/doc/numpy-1.12.0/reference/generated/numpy.ndarray.astype.html )或 struct
进行直接转换(请参阅此答案,以防万一: convert double to float in Python )。
关于python - 将 double 转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957205/