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

3
  • 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. Commented Aug 24, 2022 at 15:48
  • You might find this post to be helpful. Commented Aug 24, 2022 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. Commented Aug 25, 2022 at 8:46

1 Answer 1

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})
Sign up to request clarification or add additional context in comments.

4 Comments

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 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
@abhishek See my latest edit; I'd appreciate it if you could give it a try and let me know whether it works
Yes, I was looking for this. Tried with actual problem and It is working fine. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.