Sunday, August 26, 2012

[Matlab] fill a specific-value region with a given color

function FillIt(lon,lat,Land,FillC,TagType,FillValue)
% To fill a specific-value region with a given color
% Usage:
%            FillIt(lon,lat,Land,FillC,TagType,FillValue)
%                   TagType: could be 'RU' or 'LD', 
%                                 to fill right-up square or left-down square
%                   FillValue: nan [default] or specific value to fill with color [FillC]
%            Note: lon, lat, Land must be the same size
%      e.g.,
%            FillIt(lon,lat,lsmask,[0.0 0.3 0.3],'RU')
%      http://scriptdemo.blogspot.com

if nargin==0
   %demo
   load topo topo;
   topo(topo>0)=nan;
   xx=1:360; yy=1:180;
   [xx,yy]=meshgrid(xx,yy);
   FillIt(xx,yy,topo,[0.4 0.3 0.4],'RU');
   set(gca,'tickdir','out','linewidth',2,'xminortick','on','yminortick','on','box','on','fontweight','bold');
   set(gcf,'color','w'); axis equal; axis tight;
   return
end

if nargin==3
   FillC=[0.3 0.3 0.3];
   TagType='RU';
   FillValue='nan';
elseif nargin==4
   TagType='RU';
   FillValue='nan';
elseif nargin==5
   FillValue='nan';
elseif nargin~=6
   help FillIt;
   return
end

if numel(lon)~=numel(lat)
   disp('lon and lat must be the same size')
   return
end
if numel(lon)~=numel(Land)
   disp('lon/lat and land must be the same size')
   return
end

[Ny,Nx]=size(Land);
if ischar(FillValue)
   if strcmpi(FillValue,'nan')
      [Indy,Indx]=find(isnan(Land));
   else
      disp(['invalid fill value: ',FillValue])
      return
   end
elseif isnumeric(FillValue)
      [Indy,Indx]=find(Land==FillValue);
else
      disp('invalid fill value')
      return
end

switch upper(TagType)
   case 'RU'
      % Right Up
      % 4----3
      % |      |
      % 1----2
      Indx(Indy==Ny)=[];Indy(Indy==Ny)=[];
      Indy(Indx==Nx)=[];Indx(Indx==Nx)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx)*Ny+Indy);
      Fillx(3,:)=lon((Indx)*Ny+Indy+1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy+1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);

      Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Filly(2,:)=lat((Indx)*Ny+Indy);
      Filly(3,:)=lat((Indx)*Ny+Indy+1);
      Filly(4,:)=lat((Indx-1)*Ny+Indy+1);
      Filly(5,:)=lat((Indx-1)*Ny+Indy);
   case 'LD'
      % Left Down
      % 2----1
      % |     |
      % 3----4
      Indx(Indy==1)=[];Indy(Indy==1)=[];
      Indy(Indx==1)=[];Indx(Indx==1)=[];
      Fillx(1,:)=lon((Indx-1)*Ny+Indy);Filly(1,:)=lat((Indx-1)*Ny+Indy);
      Fillx(2,:)=lon((Indx-2)*Ny+Indy);Filly(2,:)=lat((Indx-2)*Ny+Indy);
      Fillx(3,:)=lon((Indx-2)*Ny+Indy-1);Filly(3,:)=lat((Indx-2)*Ny+Indy-1);
      Fillx(4,:)=lon((Indx-1)*Ny+Indy-1);Filly(4,:)=lat((Indx-1)*Ny+Indy-1);
      Fillx(5,:)=lon((Indx-1)*Ny+Indy);Filly(5,:)=lat((Indx-1)*Ny+Indy);
   otherwise
     disp('Not defined Fill Type')
     help FillIt
     return
end

if ~ishold; hold on; end
hf=patch(Fillx,Filly,FillC);
set(hf,'linestyle','none','tag','fillIt');

No comments:

ShowCalendar