Finding the median of a vector without using the median tool in matlab?

17 ビュー (過去 30 日間)
Amanda Mnt
Amanda Mnt 2017 年 1 月 23 日
I am struggling to find the median of a given vector (does not matter what it is) without using the median tool in matlab. Here is my current code that I have.
function median = myMedian(A)
Z=sort(A)
n=length(Z);
t=(n+1)/2
median=(Z(floor(t))+Z(ceil(t)))/2;
median=A
Some things that the code may need to address that I tried (attempted) to address is scenarios of what we would do if the vector had an even or odd amount of elements and what if the numbers are not in ascending order?
*Small note: We do not have to worry about what would happen if the vector was an empty vector
Thank you!
  5 件のコメント
Amanda Mnt
Amanda Mnt 2017 年 1 月 23 日
is the rest of the code correct then? I get an error that says:
Not enough input arguments.
Error in myMedian (line 4)
Z=sort(A)
Jorge Mario Guerra González
Jorge Mario Guerra González 2017 年 1 月 23 日
編集済み: Jorge Mario Guerra González 2017 年 1 月 23 日
Well in that error you forgot to put the input argument.
test it with:
A=rand(1,51);
med = myMedian(A)

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

回答 (1 件)

Jorge Mario Guerra González
Jorge Mario Guerra González 2017 年 1 月 23 日
All the code is fine, except for the last line.
A=rand(1,51);
Z=sort(A);
n=length(Z);
t=(n+1)/2;
med=(Z(floor(t))+Z(ceil(t)))/2
works fine for me, for both odd and even values of array length
check the answer using the actual median function.
median(A)

カテゴリ

Help Center および File ExchangeStartup and Shutdown についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by