load ~/NC/grid.mat
load ~/Aerosol_Variaiton/IRUN/SST/ncfile/SST_monthly.mat
year=1:150;
month=1:1800;

OCNFRAC=ncread('/Users/yangyang/Aerosol_Variaiton/IRUN/read_nc/ncfile/cesm.nc','OCNFRAC');
m=0;
for i=1:144
    for j=1:96
        if OCNFRAC(i,j)==1
            m=m+1;
        end
    end
end

EOF_SST=zeros(144,96);

SST_ALL=zeros(1800,m);

n=1;
for i=1:144
    for j=1:96
        if OCNFRAC(i,j)==1
            SST_ALL(:,n)=SST_MONTH(i,j,:);
            n=n+1;
        end
    end
end

[e,PC_SST,expvar] = caleof(SST_ALL,1,1);
n=1;
for i=1:144
    for j=1:96
        if OCNFRAC(i,j)==1
            EOF_SST(i,j)=e(n);
            n=n+1;
        else
            EOF_SST(i,j)=-999;
        end
    end
end

PC_SST_SMOOTH=smooth(PC_SST,59);

save('SST_EOF_monthly.mat','EOF_SST','PC_SST','expvar','PC_SST_SMOOTH')

nccreate('SST_EOF_monthly.nc','lat','Dimensions',{'lat',96},'Format','classic')
ncwrite('SST_EOF_monthly.nc','lat', lat)
ncwriteatt('SST_EOF_monthly.nc','lat','units','degrees_north')
ncwriteatt('SST_EOF_monthly.nc','lat','long_name','Latitude')
nccreate('SST_EOF_monthly.nc','lon','Dimensions',{'lon',144},'Format','classic')
ncwrite('SST_EOF_monthly.nc','lon', lon)
ncwriteatt('SST_EOF_monthly.nc','lon','units','degrees_east')
ncwriteatt('SST_EOF_monthly.nc','lon','long_name','Longitude')
nccreate('SST_EOF_monthly.nc','EOF_SST','Dimensions',{'lon',144,'lat',96},'Format','classic')
ncwrite('SST_EOF_monthly.nc','EOF_SST', EOF_SST)
nccreate('SST_EOF_monthly.nc','PC_SST','Dimensions',{'month',length(month)},'Format','classic')
ncwrite('SST_EOF_monthly.nc','PC_SST', PC_SST)
nccreate('SST_EOF_monthly.nc','PC_SST_SMOOTH','Dimensions',{'month',length(month)},'Format','classic')
ncwrite('SST_EOF_monthly.nc','PC_SST_SMOOTH', PC_SST_SMOOTH)
ncdisp('SST_EOF_monthly.nc')
