I have a python script like so:
import numpy as np
def my_function(x):
return np.array([x])
And I have a MATLAB script to call it:
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);
And it displays:
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.]
But I do not know how to actaully get the data out of this object. The type is py.numpy.ndarray
, but I want to obviously use it in MATLAB as an array or matrix, or integer or something. HOw do I convert it to one of those types?
I've been looking at these: 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
Some of the answers suggest writing to a .mat
file. I DO NOT want to write to a file. This needs to be able to run in real time and writing to a file will make it very slow for obvious reasons.
Seems like there is an answer here: "Converting" Numpy arrays to Matlab and vice versa which shows
shape = cellfun(@int64,cell(myfunction_results.shape));
ls = py.array.array('d',myfunction_results.flatten('F').tolist());
p = double(ls);
But I must say that is very cumbersome....is there an easier way?