在 MATLAB 中获取中值索引

Gac*_*cek 1 indexing matlab median

当搜索minmax值时,可以获取找到的值的索引,如下所示:

[val, index] = max(some_array_of_values);
Run Code Online (Sandbox Code Playgroud)

如何获得价值指数median

注意:
是的,我知道中位数是什么,而且我知道它有时可以是中间两个值的平均值。我想要得到的是最接近或等于中值的值的索引。
值数组包含未排序的值。我们无法对该数组进行排序 - 我需要原始数组中的索引。但我们当然可以对其副本进行排序。数组大小没有限制 - 它相对较小(大约 100 个值)

Amr*_*mro 5

这个想法是对向量​​进行排序,并取中间值。对于偶数长度向量,我们计算中间两个值的平均值。

例子:

%# 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)
Run Code Online (Sandbox Code Playgroud)

编辑

这是一个示例函数实现:

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
Run Code Online (Sandbox Code Playgroud)