MATLAB Answers

0

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

Asked by Jitesh Dadich on 4 Apr 2019
Latest activity Answered by ANKUR KUMAR on 9 May 2019
Accepted Answer by KSSV
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

  0 Comments

Sign in to comment.

2 Answers

Answer by KSSV
on 4 Apr 2019
 Accepted Answer

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

This is 0.5 x 0.5 grid data.
we can't use linspace syntax.
The thing is lat and long are varying from 8.5 to 32 and 70 to 95.5, and total range of lat and lon is 785, respectively i.e. the data are irregular & they are in first 2 rows. Rest of the matrix have corresponding values (4270 x 785)
Is there any option I can create nc file.
thank you for helping me KSSV
Attach your xlsx file.
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.


Answer by 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).

  0 Comments

Sign in to comment.