Numpy in MATLAB
I've been a user of Python for almost as long as I've been a user of MATLAB and am very comfortable with both ecosystems. As such, I have been delighted with the steadily improving interoperability between the two languages. It is extremely easy to call MATLAB code from Python and Python code from MATLAB. I use this all of the time and a particularly nice demonstration of this is the work I did with Prof. Stefan Güttel of University of Manchester where calling Python code from MATLAB was the first step in The CLASSIX Story: Developing the Same Algorithm in MATLAB and Python Simultaneously. I'll write about this in the near future but, for now, I encourage you to click on the link and watch the presentation video.
I thought it would be instructive to quickly demonstrate how easy this integration is becoming. I'll assume you've installed Python along with Numpy and made this available to MATLAB. Details on how to do this are in the documentation: Configure Your System to Use Python.
Passing Numpy arrays to MATLAB functions
Let's create a random Numpy array using numpy.random.random_sample(). One detail to be aware here of is the use of int64. The Numpy function expects integers whereas all numbers in MATLAB are of type double by default so a conversion is necessary.
npyArray = py.numpy.random.random_sample(int64([5,5]))
To pass this to a MATLAB function, simply wrap it in double to do the conversion
result = eig(double(npyArray))
Passing MATLAB arrays to Numpy
Similarly I could done this the other way around and create the random matrix using MATLAB
matlabArray = rand(5)
lets get Numpy to compute the eigenvalues. Here, no conversion is necessary. I can simply pass matlabArray to the Numpy function as if it were a Numpy array
pyEig = py.numpy.linalg.eigvals(matlabArray)
The results from some Numpy functions can be a little more complicated but they are usually straightforward to deal with. Here, for example the result is a Python object
pyEigensystem = py.numpy.linalg.eig(matlabArray)
You can get to the results as you might expect
eigValues = pyEigensystem.eigenvalues
Versions
Everything shown here was using MATLAB R2024b, Python 3,12 and Numpy 2.1.1
Over to you
Have you tried the MATLAB/Python interoperability? How did you find it?
- カテゴリ:
- Open Source,
- Python
コメント
コメントを残すには、ここ をクリックして MathWorks アカウントにサインインするか新しい MathWorks アカウントを作成します。