This short post will go over step-by-step how to use your Python functions with your MATLAB. Its actually not to difficult, the struggle is in just knowing that MATLAB gives you this ability to communicate Python with MATLAB. Let's get started!
For this, I will call short simple python file of statistic functions in MATLAB. You can see my python file in image 1. I named this file basic.py.
Image 1: basics.py file for some simple stat functions |
Now let's go through what you need to call the python. First you need to import your python module like I did in line 6 in Image 2. You can stop there, but to make life easier I recommend also including line 7 to reload the file for less manual effort each time you want to run the file.
Image 2: Importing and reloading the python file into MATLAB |
Now we can get to actually using the python functions. Let me step you through my tiny example. We have an array of numbers, x, on line 12. We want to get the mean, deviation, variance and standard deviation of this array. To do this, we call each of the python functions using the format on line 10.
Image 3: Python Function format on line 10 |
Let's actually do it. We will start by getting the mean of the array x as seen in Image 4. I do this by setting variable mean_x to be the result of python (py.) + file name + function name of x.
Image 4: Calling python function to calculate the mean of array x |
We get results of mean =15, see image 5.
Image 5: Mean of array results |
For the rest of my functions, I do the same format. I can show you below in image 6:
Image 7: Calling deviation, variance and standard deviation functions from python |
Here were the results I got for the whole program, image 8:
Congratulations, you figured out how to call python functions into MATLAB with little effort!
Before I go, let me explain a few extra notes you may have noticed on lines 19 and 20....
Those lines are just to convert the results into useable types for MATLAB to work with the rest of the python functions. You can play around with it and see how compatible/incompatible MATLAB/Python types are converted. (I recommend just looking it up, its a little tedious for this post.)
Did you learn something new from this post? Leave a comment below!
Comments
Post a Comment