アイデアは、ベクトルをソートし、中間値を取ることです。偶数長のベクトルの場合、中央の 2 つの値の平均を計算します。
例:
%# some random vector
%#x = rand(99,1); %# odd-length
x = rand(100,1); %# even-length
%# index/indices for median value
num = numel(x);
[~,ord] = sort(x);
idx = ord(floor(num/2)+(rem(num,2)==0):floor(num/2)+1);
%# median value
med = mean( x(idx) );
%# compare against MATLAB's function
median(x)
編集
関数の実装例を次に示します。
function [med idx] = mymedian(x)
%# MYMEDIAN
%#
%# Input: x vector
%# Output: med median value
%# Output: idx corresponding index
%#
%# Note: If vector has even length, idx contains two indices
%# (their average is the median value)
%#
%# Example:
%# x = rand(100,1);
%# [med idx] = mymedian(x)
%# median(x)
%#
%# Example:
%# x = rand(99,1);
%# [med idx] = mymedian(x)
%# median(x)
%#
%# See also: median
%#
assert(isvector(x));
[~,ord] = sort(x);
num = numel(x);
if rem(num,2)==0
%# even
idx = ord(floor(num/2):floor(num/2)+1);
med = mean( x(idx) );
else
%# odd
idx = ord(floor(num/2)+1);
med = x(idx);
end
end