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

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(150,m);

n=1;
for i=1:144
    for j=1:96
        if OCNFRAC(i,j)==1
            SST_ALL(:,n)=SST_ANN(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



save('SST_EOF.mat','EOF_SST','PC_SST','expvar')

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