# Thread: Creating Matlab Median Function

1. ## Creating Matlab Median Function

I first entered the code
function k=mymedian(p)
Now I have to sort the vecotr and find out how to type it out so that I can receive the median of a vector.
Does anybody understand this problem?

2. do you mean:
Code:
k=mymedian(sort(p))

3. you may also be interested in this if you dont want to use the standard matlab "sort" function.

http://www.mathhelpforum.com/math-he...or-matlab.html

Regards Elbarto

4. Thanks for the help I solved it by using the following code
function k=mymedian(p)
w=sort(p);
r=length(w);
g=floor(r/2);
k=w(g+1);
if(g*2==r)
k=(w(r)+ k)/2;
end

Does anybody have ideas on how to do the same concept for a matrice?

5. change
Code:
w=sort(p);
to
Code:
w=sort(p(:));
Code is untested but should work.

Elbarto

6. Originally Posted by elbarto
change
Code:
w=sort(p);
to
Code:
w=sort(p(:));
Code is untested but should work.

Elbarto
Code:
w=sort(p);
will work just fine.

CB

7. Originally Posted by CaptainBlack
Code:
w=sort(p);
will work just fine.

CB
This will return a sorted matrix for "w". The orginal code uses the length function so not all values will be included will they?

@OP, when finding the median of the matrix, do you only want the median of the entire matrix or the median of each column like matlab calculates?

Regards Elbarto

8. Originally Posted by elbarto
This will return a sorted matrix for "w". The orginal code uses the length function so not all values will be included will they?

@OP, when finding the median of the matrix, do you only want the median of the entire matrix or the median of each column like matlab calculates?

Regards Elbarto
The op specifies vector repeatedly. If fed a matrix it sorts the columns.

CB

9. I tried the code in #4 and got the following output:

Code:
DU>> A = magic(5)

A =

17    24     1     8    15
23     5     7    14    16
4     6    13    20    22
10    12    19    21     3
11    18    25     2     9

EDU>> mymedian(A)

ans =

11

EDU>>
It is only returning the median of the first column for me?