views:

43

answers:

1

I am trying to compile an Octave .oct function to calculate the medians of the upper and lower "halves" of a sorted vector which will vary in length e.g. for an odd length vector such as [5,8,4,6,7] I want the "lower" median value of 4,5 and 6 and the "upper" median value of 6,7 and 8 (6 is part of both calculations), and for an even length vector such as [5,8,4,6,7,9] I want the "lower" median value of 4,5 and 6 and the "upper" median value of 7,8 and 9. I am also trying to use a fast method to do this and want to use this code I have adapted and use for a straight forward median calculation:-

middle = input.length()/2 + 0.5; //middle for odd-length,"upper-middle" for even length
std::nth_element(&input(0),&input(middle),&input(input.length()) );

if (input.length() % 2 != 0) { // odd length    
median = input(middle);
} else { // even length
// the "lower middle" is the max of the lower half
lower_middle = *std::max_element( &input(0), &input(input.length()/2) );
median = ( input(middle) + lower_middle ) / 2.0;
}

I can "split" the input vector into theoretical halves with

if ( input.length() % 2 != 0) { // input vector is odd length

middle = input.length()/2 + 0.5;
std::nth_element( &input(0), &input(middle), &input(input.length()) );
// *now find median of range &input(0) to &input(middle) incl.
// *and median &input(middle) to &input(input.length()) incl.
// *using fast method given above

} else { // input vector is even length

middle = input.length()/2; // uppermost value of the lower half of the input vector  
std::nth_element( &input(0), &input(middle), &input(input.length()) );  
// *now find median of range &input(0) to &input(middle) incl.
// *and median &input(middle + 1) to &input(input.length()) incl.
// *using fast method given above

}

The problem I have is that I'm not sure of the syntax to apply the above *commented median calculations to just the indicated relevant parts of the input vector. I should perhaps mention that the input is an Octave ColumnVector input = args(0).column_vector_value() and will be between 10 to 50 values long.

A: 

if input.length() returns int than you should write

middle = input.length()/2.f + 0.5;

integer values always use integer math in c

yatagarasu