【问题标题】:How to get data from python datatype returned in MATLAB?如何从 MATLAB 中返回的 python 数据类型获取数据?
【发布时间】:2019-02-26 05:06:53
【问题描述】:

我有一个这样的 python 脚本:

import numpy as np

def my_function(x):
    return np.array([x])

我有一个 MATLAB 脚本来调用它:

clear all;
clc;
if count(py.sys.path,'') == 0
    insert(py.sys.path,int32(0),'');
end

myfunction_results = py.python_matlab_test.my_function(8);
display(myfunction_results);

它会显示:

myfunction_results = 

  Python ndarray with properties:

           T: [1×1 py.numpy.ndarray]
        base: [1×1 py.NoneType]
      ctypes: [1×1 py.numpy.core._internal._ctypes]
        data: [1×8 py.buffer]
       dtype: [1×1 py.numpy.dtype]
       flags: [1×1 py.numpy.flagsobj]
        flat: [1×1 py.numpy.flatiter]
        imag: [1×1 py.numpy.ndarray]
    itemsize: 8
      nbytes: 8
        ndim: 1
        real: [1×1 py.numpy.ndarray]
       shape: [1×1 py.tuple]
        size: 1
     strides: [1×1 py.tuple]

    [8.]

但我不知道如何真正从这个对象中获取数据。类型是py.numpy.ndarray,但我显然想在 MATLAB 中将它用作数组或矩阵,或整数或其他东西。如何将其转换为其中一种类型?

我一直在看这些:https://www.mathworks.com/help/matlab/examples/call-python-from-matlab.html https://www.mathworks.com/matlabcentral/answers/216498-passing-numpy-ndarray-from-python-to-matlab https://www.mathworks.com/help/matlab/matlab_external/use-matlab-handle-objects-in-python.html

一些答案​​建议写入.mat 文件。我不想写入文件。这需要能够实时运行,并且由于显而易见的原因,写入文件会使其非常慢。

这里似乎有答案:"Converting" Numpy arrays to Matlab and vice versa 显示

shape = cellfun(@int64,cell(myfunction_results.shape));
ls = py.array.array('d',myfunction_results.flatten('F').tolist());
p = double(ls);

但我必须说这很麻烦......有没有更简单的方法?

【问题讨论】:

    标签: python matlab numpy types numpy-ndarray


    【解决方案1】:

    目前没有将 NumPy ndarray 转换为 Matlab 数组的简单方法,但以下 Matlab 函数可以执行转换:

    function A = np2mat(X, tp)
    % Convert NumPy ndarray to a Matlab array
    if nargin < 2
        tp = 'd';
    end
    sz = int32(py.array.array('i', X.shape));
    if strcmp(tp, 'd')
        A = reshape(double(py.array.array(tp,X.flatten('F'))), sz);
    elseif strcmp(tp, 'i')
        A = reshape(int32(py.array.array(tp,X.flatten('F'))), sz);
    else
        error('Unknown data type')
    end
    

    默认数据类型为double,指定参数tp='i'转换为整数数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 2011-05-27
      • 2014-02-02
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多