% ==================================================================================================
% Module:   med.m
%
% Usage:    Returns median of a set.
%
% Purpose: 
%     Used to find the median of a set of numbers.
%
%     
% Input Variables:
%     s     vector of numbers
%     
% Returned Results:
%     The median of vector s.
%     
% Restrictions/Notes:
%
% See Also:
% 
% References:
%   median()
% 
% Author:       Justin Ford
% Date:         2/1/04
% Revisions:    none
% ==================================================================================================

function median = med(x)
	
	x_row_dim = size(x,1);
	x_col_dim = size(x,2);
	
	% If x is a matrix use rowcat() to make it a vector
	if ( (x_row_dim>1) & (x_col_dim>1) )
        x = rowcat(x);
        x_row_dim = 1;
        x_col_dim = size(x,2);
	end
	
	% max = 0;
	% ind = 0;
	
	if (x_row_dim>1)
        sorted = zeros(x_row_dim,1);
        x_dim = x_row_dim;
	else
        sorted = zeros(1,x_col_dim);
        x_dim = x_col_dim;
	end
	
	% for j=(1:x_dim)
	%     
	% %     max = -1;
	% %     
	% %     for i=(1:x_dim)
	% %     
	% %         if (x(i)>max)
	% %         
	% %             max = x(i);
	% %             ind = i;
	% %             
	% %         end
	% %         
	% %     end
	% 
	% 	[max,ind] = max(x);
	%   x(ind) = -1;
	
        sorted = sort(x);
	%     
	% end
	
	if (mod(x_dim,2)==0)
        median = (sorted(x_dim/2) + sorted(x_dim/2+1))/2;
	else
        median = sorted(x_dim/2+1/2);
	end
    