0

I am trying to convert python data to matlab format. It is saving a matlab file that has a data_array of 3x7x5 double.

But I need a file with 1x3 Cell (matlab cell) and in each cell 7x5 double matrix should be there. I tried to create list of dictionaries using these array and than save to matlab format. But that didn't helped too.

import numpy as np
import scipy.io
mat1 = np.random.randint(1,100,35).reshape(7,5)
mat2 = mat1*10
mat3 = mat1*0.1
list_mat = [mat1, mat2, mat3]
scipy.io.savemat("test_py1.mat", {'dict_array': list_mat})

Description of sample matlab file; sample_mat = scipy.io.loadma('sample_mat.mat') type(sample_mat) => dic var1 = sample_mat['key'] type(var1) => numpy.ndarray var1.shape = 1 x a var2 = var1[0,0] type(var2) => numpy.ndarray var2.shape = m x n

abhishek
  • 5
  • 2
  • 1
    It may be easier to create sample in MATLAB, and save it. Then look at the `loadmat` result, and try to replicate that. A numeric `numpy` array translates to a MATLAB matrix, though possibly with a change in `order` (and `order F` might be best). `cell` and `struct` convert to some mix of `structured array` and object dtype. – hpaulj Aug 24 '22 at 15:48
  • You might find [this post](https://stackoverflow.com/q/19797822/2476977) to be helpful. – Ben Grossmann Aug 24 '22 at 15:48
  • Thanks, I went through sample matlab file in python. I got a dictionary by `loadmat`. dictionary['key'] = numpy.ndarray with shape 1 x m. Under this numpy array there are 20 numpy.ndarray with shape a x b. But when I am trying the same with my numpy array, it is saving variable in m x a x b shape. I have added the description of sample file in my que too. – abhishek Aug 25 '22 at 08:46

1 Answers1

1

I suspect that the following will work.

import numpy as np
import scipy.io
mat1 = np.random.randint(1,100,35).reshape(7,5)
mat2 = mat1*10
mat3 = mat1*0.1
list_mat = np.empty(3,dtype = object)
list_mat[0] = mat1
list_mat[1] = mat2
list_mat[2] = mat3
scipy.io.savemat("test_py1.mat", {'dict_array': list_mat})
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • Thanks, sorry it is not giving the desired solution. It is saving all under 3 x 7 x 5 cell. But I need to save a 1 x 3 cell and under these 3 cells there should be 7 x 5 array – abhishek Aug 25 '22 at 08:59
  • @abhishek Thanks for checking and thanks for the information; I wasn't able to check with Matlab when I wrote my answer. I'll try to come up with another approach – Ben Grossmann Aug 25 '22 at 11:56
  • @abhishek See my latest edit; I'd appreciate it if you could give it a try and let me know whether it works – Ben Grossmann Aug 25 '22 at 11:59
  • Yes, I was looking for this. Tried with actual problem and It is working fine. Thanks. – abhishek Aug 25 '22 at 13:30
  • @abhishek Glad to hear it! You're welcome – Ben Grossmann Aug 25 '22 at 15:30