Prakash Prakash - 1 year ago 106
Python Question

Compare Matlab and Python variables

I am into a task where I am converting .m files to .py. But to test the code I have to dump or log values of each variables for both Python and Matlab in some log files.

Then I compare each after opening them in Excel sheet using its column property. Like what is the array index - what each index / column-row value is etc. This is very tiresome and I am not sure how we can compare variable / statements output for a specific variable programmatically in regards that it is just a .m to .py conversion.

Answer Source

You can run the program in Matlab and save all the variables using the save command. This saves to a .mat file. Then you can load the variables from that file into python using and compare them in python.

First, in matlab:

save 'data.mat' var1 var2 var3  

Then in python (in the same directory, or provide a full path):

vars ='data.mat', squeeze_me=True)
var1_matlab = vars['var1']
var2_matlab = vars['var2']
var3_matlab = vars['var3']

Note that numpy has 1D arrays, while Matlab does not (1D arrays in Matlab are actually 2D arrays where one dimension has a length of 1). This may mean that the number of dimensions in the python and scipy versions of a variable are different. squeeze_me fixes this by eliminating dimensions with a length of 1, but it may, for example, take a 2D array from Matlab that happens to just have a length of 1 in some dimension and squeezes that to a 1D python array. So you may have to do some manual dimension matching no matter what.

To get this to work, make sure matlab is configured to save files in the "MATLAB Version 5 or later" file format, though (in 2014B this is in preferences>General>MAT-Files).

If you absolutely must use version 7 files, you can try hdf5storage, which says it supports them. However, you probably have scipy already installed, and I have personally used the scipy approach and confirmed it worked but have not done the same with hdf5storage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download