将python ndarray转换为matlab矩阵

时间:2016-10-27 22:37:45

标签: python matlab python-2.7 numpy

我从matlab(R2015b)调用我创建的python模块。现在我注意到了,我们只能向python发送1xN向量。

所以我在Matlab中修复了这个问题

Matlab代码:

a = ones(3, 3);
a = a(:).';

然后我将a作为参数发送给python函数。

 m = py.computeCoreset.computecoreset(a, obj.coresetSize);

现在我的问题是python没有返回Matlab矩阵 我注意到我在调试时返回了一个ndarray。

这是我的python代码:

import numpy as np


def computecoreset(mat, coresetSize):
    return np.random.choice(mat, coresetSize)

我想我需要再次将ndarray作为矩阵

但我该怎么转换呢?

提前致谢!

3 个答案:

答案 0 :(得分:2)

https://www.mathworks.com/matlabcentral/answers/157347-convert-python-numpy-array-to-double

接受的答案表明py.array.array功能:

data = double(py.array.array('d',py.numpy.nditer(x)));

中也列出了哪些内容

https://www.mathworks.com/help/matlab/matlab_external/handling-data-returned-from-python.html

答案 1 :(得分:1)

这是一个黑暗的镜头,因为我没有Matlab来测试它,但我怀疑你必须返回一个python array对象,而不是一个numpy数组。 所以像这样:

import numpy as np
import array


def computecoreset(mat, coresetSize):
    c = np.random.choice(mat, coresetSize)
    return array.array('d', c)

答案 2 :(得分:0)

为了完整起见,另一种方式是这样的:

rnd = rand(5);
py.numpy.asarray(rnd)


  Python ndarray:

    0.3112    0.6541    0.2290    0.9961    0.0046
    0.5285    0.6892    0.9133    0.0782    0.7749
    0.1656    0.7482    0.1524    0.4427    0.8173
    0.6020    0.4505    0.8258    0.1067    0.8687
    0.2630    0.0838    0.5383    0.9619    0.0844

    Use details function to view the properties of the Python object.

    Use double function to convert to a MATLAB array.