MATLAB: How to find where the median value of a matrix occurs

matrixmediansorting

Lets say you have a matrix, X=[1,2,3,4,5,6,7,8,9].
Obviously, the median is 5, and occurs at X(1,5).
I don't care what the median value is, I want to know where it occurs.

Best Answer

By definition, the median is the middle of the sorted values (or the mean of the two middle sorted values if there is an even number), so you could just call sort, and get the middle index:
X = [1, 2, 3, 4, 5, 6, 7, 8, 9];
[~, indices] = sort(X);
medidx = indices(ceil(end/2)))