File Exchange

image thumbnail

Comparing two NetCDF files

version (13.1 KB) by Durga Lal Shrestha
nccmp compares two NetCDF files


Updated 16 Sep 2014

View License

NCCMP compares two netcdf files and prints the differences. This function is useful for testing mathematical forecasting or prediction models.


ncfile1 - name of the NetCDF file to compare
ncfile2 - name of the NetCDF file to compare
tolerance - Compare numeric data using a tolerance threshold
forceCompare - if false, exit when first difference is found
true: continues to process all variables


1. Print the differences and their locations
2. Exits when first difference is found or optionally continues to process all variables
3. User defined tolerance threshold to compare the variables

1. Specific variable inclusion or exclusion
2. Specific attribute inclusion or exclusion
3. Option to ignore the history attribute
4. Ignore difference between values that have different missing values etc

Cite As

Durga Lal Shrestha (2020). Comparing two NetCDF files (, MATLAB Central File Exchange. Retrieved .

Comments and Ratings (1)

Anthony Russel

I use this script all the time and have found it incredibly helpful for verifying only intended variables have changed after making an update to my software that creates NetCDFs. The only thing I have run into is a case where one file ends up getting a NaN and the other file has an actual value in it at a certain index. To solve this I added this block of code after line 203 (under the data2=ncread(ncfile2,comName{i}); line):
% check for differences in NaNs
ind = find(isnan(data1) ~= isnan(data2));
if ~isempty(ind)
filesAreIdentical = false;
if forceCompare
for j=1:length(ind)
%[I1,I2,I3] = ind2sub(size1,ind(j));
X = ind2sub1(size1,ind(j));
fprintf('DIFFER: NaNs in VARIABLE, %s : POSITION %s: VALUES: %12.20G <> %12.20G \n' ,comName{i},num2str(X),data1(ind(j)),data2(ind(j)))
% Just report the first occurrence
fprintf('DIFFER: NaNs in VARIABLE, %s : NUMBER OF LOCATION %d, Reporting the first location only...\n' ,comName{i},length(ind))
X = ind2sub1(size1,ind(1));
fprintf('DIFFER: NaNs in VARIABLE, %s : POSITION %s: VALUES: %12.20G <> %12.20G \n' ,comName{i},num2str(X),data1(ind(1)),data2(ind(1)))


1. Remove dependency of third party function by adding internal ind2sub1 function
2. Formatting the texts

MATLAB Release Compatibility
Created with R2014a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Tags Add Tags