
library(ncdf4)
#library(easyNCDF)

in.file <- paste("C_Matrix.nc",sep="")  # input file
innc <- nc_open(in.file)
ivar.name <- "cor" # input varname
idat <- ncvar_get(innc,ivar.name)
idat <- (idat)
A.svd <- svd(idat)

# write to text file
#write.table(round(A.svd$d,digits=3),'old_d.txt',col.names = F,row.names = F)
#write.table(round(A.svd$u,digits=3),'old_u.txt',col.names = F,row.names = F)
#write.table(round(A.svd$v,digits=3),'old_v.txt',col.names = F,row.names = F)

#write to ncdf
# for u
u <- A.svd$u
col <- seq(ncol(u))
row <- seq(nrow(u))
dim_x <- ncdim_def('lon','degrees_east',col)
dim_y <- ncdim_def('lat','degrees_north',row)
var_out <- ncvar_def("var",units="",list(dim_y,dim_x),-9999)
ofile=paste("u.nc",sep="")
ncid_out <- nc_create(file=ofile,list(var_out))
ncvar_put(ncid_out,var_out,(u))
nc_close(ncid_out)

# for v
v <- t(A.svd$v) # for transpose 
col <- seq(ncol(v))
row <- seq(nrow(v))
dim_x <- ncdim_def('lon','degrees_east',col)
dim_y <- ncdim_def('lat','degrees_north',row)
var_out <- ncvar_def("var",units="",list(dim_y,dim_x),-9999)
ofile=paste("v.nc",sep="")
ncid_out <- nc_create(file=ofile,list(var_out))
ncvar_put(ncid_out,var_out,(v))
nc_close(ncid_out)

# for d
d <- as.matrix(A.svd$d)
col <- seq(ncol(d))
row <- seq(nrow(d))
dim_x <- ncdim_def('lon','degrees_east',col)
dim_y <- ncdim_def('lat','degrees_north',row)
var_out <- ncvar_def("var",units="",list(dim_y,dim_x),-9999)
ofile=paste("w.nc",sep="")
ncid_out <- nc_create(file=ofile,list(var_out))
ncvar_put(ncid_out,var_out,(d))
nc_close(ncid_out)

