median

Parameters

withAsSlice T

input that satisfies hasAsSlice

Examples

Median of vector

import mir.ndslice.slice: sliced;

auto x0 = [9.0, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5].sliced;
assert(x0.median == 5);

auto x1 = [9.0, 1, 0, 2, 3, 4, 6, 8, 7, 10].sliced;
assert(x1.median == 5);

Median of dynamic array

auto x0 = [9.0, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5];
assert(x0.median == 5);

auto x1 = [9.0, 1, 0, 2, 3, 4, 6, 8, 7, 10];
assert(x1.median == 5);

Median of matrix

import mir.ndslice.fuse: fuse;

auto x0 = [
    [9.0, 1, 0, 2,  3], 
    [4.0, 6, 8, 7, 10]
].fuse;

assert(x0.median == 5);

Row median of matrix

import mir.algorithm.iteration: all;
import mir.math.common: approxEqual;
import mir.ndslice.fuse: fuse;
import mir.ndslice.slice: sliced;
import mir.ndslice.topology: alongDim, byDim, map;

auto x = [
    [0.0, 1.0, 1.5, 2.0, 3.5, 4.25], 
    [2.0, 7.5, 5.0, 1.0, 1.5, 0.0]
].fuse;

auto result = [1.75, 1.75].sliced;

// Use byDim or alongDim with map to compute median of row/column.
assert(x.byDim!0.map!median.all!approxEqual(result));
assert(x.alongDim!1.map!median.all!approxEqual(result));

Can allow original slice to be modified or set output type

import mir.ndslice.slice: sliced;

auto x0 = [9.0, 1, 0, 2, 3, 4, 6, 8, 7, 10, 5].sliced;
assert(x0.median!true == 5);

auto x1 = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10].sliced;
assert(x1.median!(float, true) == 5);

Arbitrary median

assert(median(0, 1, 2, 3, 4) == 2);

For integral slices, can pass output type as template parameter to ensure output type is correct

import mir.ndslice.slice: sliced;

auto x = [9, 1, 0, 2, 3, 4, 6, 8, 7, 10].sliced;
assert(x.median!float == 5f);

auto y = x.median;
assert(y == 5.0);
static assert(is(typeof(y) == double));

Meta