Matlab call Python script
Recent attempts to call Python script in Matlab environment, summed up several problems encountered under here.
1. Python module load
In Matlab function, you want to file as a Python module is loaded, you need to modify the Python environment variable path
P = py.sys.path;
if count(P,modpath) == 0
insert(P,int32(0),modpath);
end
After modifying the good path, directly using the import command to load the Python module produces an error, need to use the following command
py.importlib.import_module ( 'analytical_subcritical');% loading module analytical_subcritical python
2. Python function calls
When the function is called module Python, Matlab environment variables need to be passed to the function for converting the Python type variable, the variable can be some types of direct conversion, refer to official website Matlab -The data is passed to Python。
Commonly used vectors and matrices in Matlab convert 1\(\times\)Size N may be directly used asarray.array('d') Python variable incoming type, so may be input directly into the Python function calculates the data size after the conversion.
3. Python data processing
After obtaining the Python function returns a result, the need to re-convert the data type of the variable Matlab. You can refer to different types of conversion variables official website -Processing the data returned from the Python。
However, these types Python only partially built-in variable type, commonly used for the library returns Numpyndarray Type variables need to be further transformed
value =
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×24 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: 24
ndim: 1
real: [1×1 py.numpy.ndarray]
shape: [1×1 py.tuple]
size: 3
strides: [1×1 py.tuple]
[1 2 3]
For this type of variable conversion process, there are two methods.
The first way is tondarray Variable into the Pythonarray.array Type, using a double function may then be converted directly into Matlab variables.
data = double(py.array.array('d',py.numpy.nditer(value))); %d is for double, value is ndarray
The second is the use of scipy library will be stored as a variable mat file, then loaded in Matlab.
import numpy as np
import scipy.io
x = np.linspace(0, 2 * np.pi, 100)
y = np.cos(x)
scipy.io.savemat('test.mat', dict(x=x, y=y))
Compared to the second method, the first method is more direct. Matlab converted to a variable size to reshape using vector modification.