我想从 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/