function y=minfilt2(x,MN)
%minfilt2 Two-dimensional minimum-filtering.
%	y=minfilt2(x,[M N]) performs minimum filtering of the image x in
%	two dimensions, using a MxN neighborhood. M and N are assumed to be
%	odd. If M and N are not given, they are assumed to be 3.
%	See also: maxfilt2

% If changes are made, make the corresponding changes to maxfilt2 as well

if nargin<2,
  MN=[3 3];
end
M=MN(1); N=MN(2);
[rows,cols]=size(x);

y=x;

for i=1:(M-1)/2,
  y = min(min(y,[x(i+1:rows,:);x(rows*ones(1,i),:)]),...
      [x(ones(1,i),:);x(1:rows-i,:)]);
end

x=y;

for j=1:(N-1)/2,
  y = min(min(y,[x(:,j+1:cols) x(:,cols*ones(1,j))]),...
      [x(:,ones(1,j)) x(:,1:cols-j)]);
end