function [Y, I] = median(X)
%[Y, I] = median(X)
%The median find the median element of X
%if X is a vector, the median element and its index is returned.
%if X is a matrix, the median function operates columnwise, returning
%a row vector with elements corresponding to the median of each column
%in X and a row vector whose elements are the index of the median in
%each column.

%       S.Halevy 7/31/92
%       Copyright (c) 1992 by the MathWizards

if (nargin ~= 1)
   error('median function needs 1 argument');
end

if ( isrow(X) )
   X = X';
end
[r, c] = size(X);
[sX, sI] = sort(X);
Y = zeros(1, c);
I = Y;
for iter=1:c
   row = floor( max( size(sI(:,iter)) ) / 2 + 1 );
   Y(iter) = sX(row, iter);
   I(iter) = sI(row, iter);
end
