function res=rebin(a,n);
%REBIN - average values of a matrix by bloc
%
%   INPUT a,n, where a is the matrix, and n the size of the area averaged around
%   one pixel
%
%   Usage:
%      res=rebin(a,n)

s=size(a);

if (mod(s(1)/n,2)~=0 | mod(s(2)/n,2)~=0),
   disp('Cannot rebin, the dimensions of the matrix and n are not compatible');
   break
end

res=zeros(s(1)/n,s(2)/n);

for m=1:s(1)/n,
   for l=1:s(2)/n,
      if sum(sum(~isnan(a((m-1)*n+1:m*n,(l-1)*n+1:l*n))))~=0,
      res(m,l)=sum(...
                   sum(...
                       ~isnan(...
                              a((m-1)*n+1:m*n,(l-1)*n+1:l*n)...
                              ).*...
                       a((m-1)*n+1:m*n,(l-1)*n+1:l*n)...
                       )...
                   )...
                   /sum(sum(~isnan(a((m-1)*n+1:m*n,(l-1)*n+1:l*n))));
             else
                res(m,l)=NaN;
             end
             
   end
end

   






