Sep 29, 2010

Tips: Import MATLAB MAT-files

You want to import the “.mat” file:

Import[“Helheim.mat”]

Import::fmterr: Cannot import data as MAT format. >>

Don’t panic. Since the version 7.3 (2006b), Matlab actually saves mat files using the HDF5 format by default. So pretty much every mat file you work with nowadays is in HDF5 format. Let’s try it again.

Import["Helheim.mat", "HDF5"]

{"/Data", "/Depth", "/Distance", "/Latitude", "/Longitude",  "/UTC_time"}

data = Import["Helheim.mat", {"HDF5", "Datasets", "/Data"}];

Then we can generate a beautiful plot in Mathematica.

viewmat

For who may wonder what this image is, it is the radar image shows underground ice-thickness, more information can be found at The Center for Remote Sensing of Ice Sheets (CReSIS)

3 comments:

Simon said...

Hm, it seems this does not work with files generated by Matlab 7.11 (R2010b).

For those, import as .MAT format does not seem to fail though -- except for throwing a few errors for big files, typically; and only importing first element of struct arrays. I had hoped the trick shown here would solve this, but no such luck.

ssssss said...

Please, include also the code and/or method how you plot the data here for simple testing. Your post is very popular about the topic in Google.

Beerman58 said...

I did get this to work well with MATLAB R2020a and Mathematica 12.1, but there is a trick; you must save your .mat file in MATLAB under the old version, as if for backward compatibility, e.g. with this command:

save( 'filenameout_HDF5.mat', 'StructVariableName', '-v7.3' ) % syntax credit URL

Why? Here in December 2020, I guess file formats have diverged enough, that getting .mat files into Mathematica is apparently a major problem once again. (At least it was for the output of my Siemens/LMS brand data acquisition system.)

P.S. - In case anyone else is dealing with these deeply-nested 'struct' types, after the above .mat file conversion, you can dive-in and pluck out only the buried, matrix-type data payload from within Mathematica like this:

Import["C:\\Full\\Folder\\Path\\filenameout_HDF5.mat", {"HDF5", "Datasets","/StructVariableName/y_values/values"}]

Other good Mathematica-side HDF5 import references here (StackExchange RE internal HDF5 paths/parameters) and here (Wolfram language manual).