How to create nc file having lat, long, time, and 2D matrix

73 views (last 30 days)
Jitesh Dadich
Jitesh Dadich on 4 Apr 2019
Answered: ANKUR KUMAR on 9 May 2019
Helo everyone,
I am trying to create a .nc file which will have lat, long, time and 2D matrix simultaneously.
I have loaded lat, long, and time parameters , but how will I put the corresponding 2D matrix for each lat long and time while creating .nc file.
The answer should come in a matrix which has time in 1st column, lat and long in 1st & 2nd rows, and parameter values corresponding to time and lat_long.
Thank you in advance

Accepted Answer

KSSV
KSSV on 4 Apr 2019
Refer this demo example:
% nc filename to be written
file = 'myfile.nc' ;
%% Write lon and lat variables
% Get data
lon = 1:10 ;
lat = 1:10 ;
nx = length(lon) ;
nccreate(file,'lon','Dimensions',{'lon',1,nx},'DeflateLevel',7) ;
ny = length(lat) ;
nccreate(file,'lat','Dimensions',{'lat',1,ny},'DeflateLevel',7) ;
nccreate(file,'time','Dimensions',{'time',1,Inf},'DeflateLevel',7) ;
nccreate(file,'z','Dimensions',{'lon','lat','time'},'DeflateLevel',7) ;
for i = 1:10
ncwrite(file,'time',i,i) % write time
data = rand(10) ;
ncwrite(file,'z',data,[1,1,i]) ; % write 3D data
end
  14 Comments
Jitesh Dadich
Jitesh Dadich on 5 Apr 2019
Here I have attached a small file of my excel file.
Time is varying from 3rd row to 52 row in 1 st column and first 2 row has lon and lat.

Sign in to comment.

More Answers (1)

ANKUR KUMAR
ANKUR KUMAR on 9 May 2019
I hope this helps.
[data]=xlsread('test.csv');
lat=data(2,2:end);
lon=data(1,2:end);
vardata=data(3:end,2:end);
vardata(:,size(vardata,2)+1)=nan; %dummy column just to put nan over the points where data is not available
longitude=unique(lon);
latitude=unique(lat);
[lon_m,lat_m]=meshgrid(longitude,latitude);
index=arrayfun(@(x,y) find(lon==x & lat==y),lon_m,lat_m,'uni',0);
index(cellfun('isempty',index))={-9999.99};
datavar=str2double(string(index)); datavar(datavar==-9999.99)=786;
out=arrayfun(@(x) reshape(vardata(x,datavar),[48 51]),1:50,'uni',0);
outputdata=cat(3,out{:});
nccreatewrite('test.nc','lat',{'lat','c'},latitude')
nccreatewrite('test.nc','lon',{'lon','c'},longitude')
nccreatewrite('test.nc','TC',{'lat','lon','days'},outputdata)
You can check the validity of the above data by typing
squeeze(outputdata(latitude==32,longitude==75.5,:))
The output of the above line is the same as the second column in the excel file (of course by skipping the first two rows).

Community Treasure Hunt

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

Start Hunting!

Translated by