Skip to content Skip to sidebar Skip to footer

Saving Dictionaries From Python To Matlab With Scipy

I'm finding some problems to save my neat generated data into .mat files. I thought it was more straightforward with Scipy, but it seems I'm getting something wrong. This is an exa

Solution 1:

The issue is that a string in MATLAB and Octave is really just an array of characters, so the following statement is actually a 3D array

[['rock', 'metal']]

If we replace the characters with numbers to make it a little clearer that it's a 3D array we get something like this

[[[1,2,3], [4,5,6]]]

When you save either of these to a .mat file with savemat it's going to be treated as a 3D array.

If you instead want a cell array, you have to manually create a numpy array of numpy objects.

import scipy
import numpy as np

out = {'tags': np.array(['rock', 'metal'], dtype=np.object)}

scipy.io.savemat('test.mat', out)

Then within MATLAB or Octave

data = load('test.mat')
%    tags =%    {%      [1,1] = rock%      [1,2] = metal%    }

Update

In the case of a nested cell array, each level that you would like to be a cell array must also be a numpy array of numpy objects

out = {'tags': np.array([
            np.array(['classical', 'pop'], dtype=np.object),    # A nested cell array'classical', 'classical', 'classical'], dtype=np.object)}

Post a Comment for "Saving Dictionaries From Python To Matlab With Scipy"