python - 将 MATLAB 矩阵对象转换为 Python NumPy 数组

标签 python matlab numpy matrix multidimensional-array

我想从 MATLAB 调用一些 python 代码,为此我需要将矩阵对象转换为 NumPy ndarray ,通过MATLAB函数py.numpy.array 。但是,仅将矩阵对象传递给函数是行不通的。目前,我解决了将矩阵转换为单元格对象的问题,其中包含矩阵的行。例如

function ndarray = convert(mat)
    % This conversion fails
    ndarray = py.numpy.array(mat)

    % This conversion works
    cstr = cell(1, size(mat, 1));
    for row = 1:size(mat, 1)
        cstr(row) = {mat(row, :)};
    end
    ndarray = py.numpy.array(cstr);

我想知道是否存在更有效的解决方案。

最佳答案

假设您的数组包含 double 值,该错误会准确地告诉我们应该做什么:

A = magic(3);
%% Attempt 1:
try 
npA = py.numpy.array(A);
% Result:
%   Error using py.numpy.array
%   Conversion of MATLAB 'double' to Python is only supported for 1-N vectors.
catch
end
%% Attempt 2:
npA = py.numpy.array(A(:).');
% Result: OK!

然后:

>> whos npA
  Name      Size            Bytes  Class               Attributes

  npA       1x1                 8  py.numpy.ndarray   

之后您可以使用numpy.reshape直接在 MATLAB 或 Python 中恢复原始形状。

关于python - 将 MATLAB 矩阵对象转换为 Python NumPy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41705238/

相关文章:

python - 在 Python 中将时区偏移量应用于日期时间

python - 无法通过 pip 安装 Scipy

matlab - 如何自动标准化多个直方图以达到相同的最大水平?

MATLAB:用 imshow 标记轴

python-3.x - 如何使用一些概率值在整个幻灯片图像(.svs 格式)上生成热图?

python - 二维数组中每个对角线的最大值

python - 循环检测系统挂起

python - 使用 readlines 读取前 N 行

python - 如何有效地加载稀疏矩阵?

python - 无法将稀疏矩阵写入 csv