There and back again: A Matlab array's tale by Bob Turner
Some talk the other day about porting and interoperability between Matlab and Python, so I thought I'd investigate passing arrays back and forth...
I'm doing this (against Mathworks advice) in an Anaconda environment. However, starting Matlab from the Anaconda command prompt seemed to work fine.
Matlab version is:
My plan, here, is to make a big array in Matlab, convert it to a Python numpy array, do some manipulation of it (transpose it a couple of times) and then turn it back into a Matlab array. By way of an experiment, I'll time each step.
Firstly, we make a Matlab array of random numbers:
Next, out of curiosity, we do the same thing in Python:
Surprisingly faster than Matlab. By a lot. Perhaps the array is being generated at a lower precision? Right at the bottom of this block we see that it's a float64 which I think is the same as a Matlab double:
I'll transpose the array twice in Matlab (which should tax the computer but give me the same variable out as I put in:
...which I can check like this:
...and it is. Obviously. Next, I'll turn the Matlab array into a Python array (using numpy):
Or by saving a .mat file and reloading:
py.importlib.import_module("scipy"); %needs scipy which is not imported by default
Fine, but slow.
Transpose twice as in Matlab:
Convert back to Matlab:
...and test that the variable that's been converted to Python, transposed twice and converted back to Matlab is unchanged:
Looks like it's survived the ordeal!
This is good news and suggests that calling Python from Matlab might be do-able.
What surprises me about this is that despite everything being called from Matlab, the Python operations seem to be going way faster. Could be I'm missing something crucial, here. Not generalisable! If so I'd love to hear about it at bob.turner.uk at gmail.com or @Bobatron on Twitter!