3

I am importing a matlab file using scipy.io, and trying to find its dimensions. It seems, even though the file is getting loaded into python, it's not able to give the dimensions. Why is that? And how to fix this?

>>> import scipy.io
>>> pref_mat = scipy.io.loadmat('pref_mat_loc.mat')
>>> R=pref_mat
>>> import numpy
>>> R=numpy.array(R)
>>> len(R)
0
>>> R # We see that the first line of the file is getting printed, means the file has been loaded.

array({'pref_mat': array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16), '__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017', '__version__': '1.0', '__globals__': []}, dtype=object)

>>> len(R.shape) # But it appears here as though R is empty
0
>>> R.shape # As does here
()
5
  • len(R.shape) is the same as R.ndim for future reference. Commented May 9, 2017 at 16:28
  • What is the purpose of R=pref_mat? Why not just R = scipy.io.loadmat(...)? Commented May 9, 2017 at 16:29
  • 1
    Why in the name of ... are you doing R=numpy.array(R)? Do you understand what loadmat returns? Commented May 9, 2017 at 16:29
  • @MadPhysicist Why? What happened? I am not a regular python user, I just happpen to require it for this particular job. As I understand, loadmat loads the matlab file; I don't know what it returns though. Is it a dictionary? Commented May 9, 2017 at 16:35
  • 1
    It sure does. Have a look at your own output and the docs Commented May 9, 2017 at 16:36

1 Answer 1

3

pref_mat, returned by loadmat is a dictionary. You have wrapped it in an array, R. I can deduce the contents of pref_mat as the {} part of R:

{'pref_mat': array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ...,
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint16), 
'__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Mon May 08 23:42:05 2017', 
'__version__': '1.0', 
'__globals__': []}

So the array you are interested in is

R = pref_mat['pref_mat']

That R should have the shape and dtype that you want. Though in summary view I only see 0's.

If the MATLAB had saved cells or structs the nesting of 'object' type arrays would get more complicated.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok, thanks. It works. The data is ok, its a sparse matrix, hence the 0s. :)

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.