如何将Python列表转换为列向量?

2024-06-16 12:51:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用MATLAB中的fitdist方法,其中x为: enter image description here

我尝试了不同的方法来解决这个问题,它们都给出了相同的错误:

eng.fitdist(eng.cell2mat(list(x)), 'stable')
eng.fitdist(matlab.double(list(x)), 'stable')
eng.fitdist(list(x), 'stable')

所有这些都给了我一个错误:

MatlabExecutionError:  
        File C:\Program Files\MATLAB\R2020b\toolbox\stats\stats\fitdist.m, line 126, in fitdist X must be a numeric column vector.

你知道怎么摆脱它吗?如何将列表转换为使用MATLAB的列向量? 我使用的是MatlabR2020B


Tags: 方法stats错误filesprogramenglistfile
1条回答
网友
1楼 · 发布于 2024-06-16 12:51:23

您可以使用matlab.doublesize参数来创建列向量

MATLAB中的列向量等价于二维矩阵,其第二维度大小等于1。
例如:大小为[5, 1]的矩阵是包含5列的列向量

根据文件,MATLAB Arrays as Python Variables
matlab.double有一个可选的size参数:

matlab.double(initializer=None, size=None, is_complex=False)

可以将size参数设置为(x.size, 1)以创建列向量

以下语法有效(假设x是NumPy数组):

eng.fitdist(matlab.double(list(x), (x.size, 1)), 'stable')

以下语法也适用:

eng.fitdist(matlab.double(list(x), (len(list(x)), 1)), 'stable')

以下代码用于测试:

import numpy as np
import matlab
import matlab.engine
eng = matlab.engine.start_matlab()

x = np.array([176.0, 163.0, 131.0, 133.0, 119.0, 142.0, 142.0, 180.0, 183.0, 132.0, 128.0, 137.0, 174.0])

eng.fitdist(matlab.double(list(x), (x.size, 1)), 'stable')

更新:

在Python中读取fitdist的结果:

读取结果具有挑战性,因为fitdist返回类型为'prob.StableDistribution'的对象。
以数组的形式获取结果会更容易。
我的建议是创建一个返回数组的MATLAB“包装函数”

例如:

MATALB代码文件my_fitdist.m

function y = my_fitdist(x)
if (size(x, 1) == 1), x = x.';end % Make sure input is a column array.
s = fitdist(x, 'stable');
y = [s.alpha, s.beta, s.gam, s.delta]; % Put the output of fitdist in an array

Python代码:

import numpy as np
import matlab
import matlab.engine
eng = matlab.engine.start_matlab()

x = np.array([176.0, 163.0, 131.0, 133.0, 119.0, 142.0, 142.0, 180.0, 183.0, 132.0, 128.0, 137.0, 174.0])

y = eng.my_fitdist(matlab.double(list(x))) # Execute the wrapper function "my_fitdist"

可能有更好的解决方案,但我没有使用MATLAB引擎的经验

相关问题 更多 >