2

This is a MATLAB question: the problem is caused by interactions with MATLAB files and Python/numpy. I am tying to write a 3-D array of type uint8 in MATLAB, and then read it in Python using numpy. This is the MATLAB code that creates the file:

voxels = zeros(30, 30, 30);
....
fileID1 = fopen(fullFileNameOut,'w','s');
fwrite(fileID1, voxels, 'uint8');
fclose(fileID1);

This is the Python code that tries to read the file:

filename = 'File3DArray.mat'
arr = scipy.io.loadmat(filename)['instance'].astype(np.uint8)

This is the error that I get when I run the python code:(I think this is the source of the problem. What is MM

raise TypeError('Expecting miMATRIX type here, got %d' % mdtype)

This is the output of the Linux command 'file' on the 3D array file that I created (I think this is the source of the problem. What is MMDF Mailbox?):

File3DArray.mat: MMDF mailbox

This is the output of the same Linux command 'file' on another 3D array file that was created by someone else in MATLAB:

GoodFile.mat: Matlab v5 mat-file (little endian) version 0x0100

I want the files I create in MATLAB to be the same as GoodFile.mat (so that I can read them with the Python/Numpy code segment above). The output of the Linux 'file' command should be the same as the GoodFile output, I think. What is the MATLAB code that does that?

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
JB_User
  • 3,117
  • 7
  • 31
  • 51
  • `file` looks at (among other things) the first few bytes of a file and compares them against magic strings. This is likely the reason it is identifying your file as a "MMDF mailbox", whatever what is. Your first few bytes of data just happen to match. – Cris Luengo Dec 18 '18 at 21:30

1 Answers1

2

To create a MAT-file, use the MATLAB save command:

voxels = zeros(30, 30, 30, 'uint8');
save(fullFileNameOut, 'voxels', '-v7')

You need to add '-v7' (or '-v6') as an argument to save to create a file in an older format, as SciPy doesn't recognize the '-v7.3' files created by default.

Cris Luengo
  • 55,762
  • 10
  • 62
  • 120
  • Okay. But the error mentions 'v5'. Should I use a '-v5' argument? – JB_User Dec 18 '18 at 21:36
  • Okay '-v6' worked (there is no '-v5' option). Thanks. I never would have figured that out on my own. – JB_User Dec 18 '18 at 21:58
  • 1
    To read v7.3 matlab in python, use [h5py](https://docs.h5py.org). For example, `import h5py; f = h5py.File( 'my.mat', 'r' ); x = np.array( f.get( 'data/x' ))` – denis Apr 20 '20 at 15:33