3
$\begingroup$

I am using Mma 9.0

I am trying to export an array with Dimensions {5,100,160,160} to a .mat-file using the Export command, but it is not working and I get the following error instead:

Export::type: "{<<1>>} cannot be exported to the !(\"MAT\") format."

I have tried exporting data[[i]] separately, and then it works but then I am stuck with 5 separate files.

Why and what to do?

$\endgroup$
  • $\begingroup$ The problem arises in version 10.1 as well... clearly a bug which must get fixed. $\endgroup$ – David G. Stork May 7 '15 at 14:49
  • $\begingroup$ @DavidG.Stork and rhermans: This is not a bug. MAT4 does not support multidimensional arrays, only matrices. Mathematica only exports to MAT4. $\endgroup$ – Szabolcs Oct 17 '15 at 8:47
3
$\begingroup$

Since you know the dimensions of the array when you are importing it back, the quickest solution is to Flatten the array before you export it as a MAT file, and then ArrayReshape it back when you want to use it.

testArray = Array[#1 + #2 - #3 - #4 &, {1, 1, 2, 2}]
(* {{{{0,-1},{-1,-2}}}} *)
Export["test.mat", testArray]
Export::type: {{{{0,-1},{-1,-2}}}} cannot be exported to the MAT format. >>
(* But you can flatten it *)
Export["test.mat", Flatten[testArray]]
(* "test.mat" *)
importedArray = ArrayReshape[Import["test.mat"], {1, 1, 2, 2}];
testArray == importedArray
(* True *)
$\endgroup$
  • 1
    $\begingroup$ That's a good advice. An improvement for robustness might be that the first few elements of the flattened array will describe its dimensions. i.e. Flatten[{Depth[arr],Dimensions[arr],arr}]. $\endgroup$ – yohbs Oct 8 '15 at 20:34
1
$\begingroup$

This is not a bug.

Mathematica can only export to the version 4 MAT format, as documented. This format only supports matrices, but not 3 or higher dimensional arrays.

When trying to export a 3D array, Mathematica will in fact export a list of matrices, each of which will be assigned to a separate variable in MATLAB. When passing a 4D array to Export, it will simply fail as this is an unsupported format, as the Export::type message indicates.


What can you do then? That depends on why you want a MAT format in the first place. If it's because you need to use it in some software other than MATLAB, then just try a different format. If that software only supports MAT version 6 files, and you have no access to MATLAB, then you are out of luck.

If you just want to send the data to MATLAB, then use MATLink or export to HDF5 instead. MATLAB's own v7.3 MAT files are in fact HDF5 files with a specific structure.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.