2

I have a 10 x 10 array of values, A. I need the median, M, of all of those values. I can find the medians along the rows or along the columns easily:

M = median(A,1) %or
M = median(A,2)

However, M = median(A) also returns the medians along the rows.

How can I find a single median of ALL the values? I know I could convert the array to one very very long vector, but that seems unpleasant and inefficient. Is there a simpler solution? I would like to be able to do this for multi-dimensional arrays as well.

Thanks!

rayryeng
  • 102,964
  • 22
  • 184
  • 193
Takver
  • 172
  • 1
  • 3
  • 13
  • 2
    Converting a matrix to a single vector is one of the **fastest** operations you can perform in MATLAB. Remember that memory in MATLAB is arranged in column-major order and so actually using multiple dimension access indices to get the right memory location is syntactic sugar to multidimensionally access an element with a single index. Luis's suggestion below to unroll the matrix into a long vector and performing the median... you can't get it any faster. – rayryeng May 27 '16 at 23:13
  • 1
    Perfect! I overestimated the time-consuming-ness of converting. Thanks! – Takver May 27 '16 at 23:17
  • Please accept the answer by Luis to let the community know you no longer need help. – rayryeng Jun 12 '16 at 01:06

1 Answers1

6

First linearize by indexing with (:). This transforms any array into a column array. Then compute the median:

M = median(A(:));

I don't think that indexing with (:) needs any memory reallocation. It just reads the array in column-major order.

Community
  • 1
  • 1
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147