.mat files with the same data are different

6 views (last 30 days)
I'd like to diff two .mat files via the command line. However, it appears that the .mat files contains somewhat different data, even if (I think) they ought to be the same.
>> a = 3
a =
>> save('/<location>/filename.mat', 'a')
>> clear
>> a = 3
a =
>> save('/<location>/filename2.mat', 'a')
From the command line:
[matquest@computer <location>]$ diff filename.mat filename2.mat
Binary files filename.mat and filename2.mat differ
However, I can load the files and compare using isequaln and it returns true.
What is causing this difference? And is there a way to save the .mat files so that I can compare them using diff?

Accepted Answer

Stephen23 on 29 Jan 2018
Edited: Stephen23 on 29 Jan 2018
.mat files include a timestamp, so the binary files will clearly be different if they were created even just one millisecond apart. A naive binary comparison is therefore useless.
Read more about the file format here:
Steven Lord
Steven Lord on 30 Jan 2018
You could configure your source control system to use the differencing and merging tools provided by MathWorks for our file formats.

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 29 Jan 2018
There is no way to save the .mat files so that you can compare them using binary diff.
.mat files include information about the time of creation.
Remember too that different .mat files might have the same data in a different order.
Also, when a .mat file is updated using save with the -append flag, then "holes" can be left in the .mat file -- when the new version of a variable is larger than the old version with the same variable name, and it is not the last variable in the file, then MATLAB marks the old space as unused and writes the new version at the end of the file (or perhaps at the first place in the .mat file where it finds enough available space.) Therefore .mat files that load the same data might not have the same size (because one might have holes) or same order.
If object-oriented objects are saved, then in some cases two objects might look the same but have different serialization. Information about serialization in MATLAB is not easy to find, but at least in some programming systems, serialization can involve keeping "generation number" (incremented on every write to the object, or sometimes to the structure of the object) to allow easy determination of who has the newer version of the content.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by