Help with calculating median of an array without using built in function?

8 ビュー (過去 30 日間)
Martin Kao
Martin Kao 2016 年 3 月 26 日
コメント済み: DGM 2023 年 9 月 27 日
A=[8 6 7 5 3 0 9]
b=sort(A)
b= 0 3 5 6 7 8 9
Now what are the next steps?

採用された回答

Roger Stafford
Roger Stafford 2016 年 3 月 26 日
Next step:
n = length(b);
t = (n+1)/2;
md = (b(floor(t))+b(ceil(t)))/2; % <-- median
  2 件のコメント
Martin Kao
Martin Kao 2016 年 3 月 26 日
Thank you so much! What would the steps look like if there were an even number of terms?
Roger Stafford
Roger Stafford 2016 年 3 月 26 日
Same formula works for odd and even numbers:
1. even, say, n = 10, t = (10+1)/2 = 5.5, floor(t) = 5, ceil(t) = 6,
md = (b(5)+b(6))/2 (average of middle two values)
2. odd, say, n = 13, t = (13+1)/2 = 7, floor(7) = 7, ceil(7) = 7,
md = (b(7)+b(7))/2 = b(7) (center value)

サインインしてコメントする。

その他の回答 (2 件)

Azzi Abdelmalek
Azzi Abdelmalek 2016 年 3 月 26 日
use n=numel(A) to get the number of element in A. If n is odd, the median will be b((n+1)/2), if n is even, try to find out.
  1 件のコメント
Martin Kao
Martin Kao 2016 年 3 月 26 日
N=7. The correct answer is 6. How would you solve this?

サインインしてコメントする。


William
William 2023 年 9 月 27 日
Heres a quicker way:
sortedvec = sort(vec)
l = length(sortedvec)
x = (l + 1) / 2
median = sortedvec(x)
  1 件のコメント
DGM
DGM 2023 年 9 月 27 日
That will fail if the vector length is even.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by