【问题标题】:Medians of upper and lower halves of a vector向量的上半部和下半部的中位数
【发布时间】:2011-03-13 09:27:55
【问题描述】:

我正在尝试编译一个 Octave .oct 函数来计算排序向量的上下“一半”的中位数,该中位数的长度会有所不同,例如对于奇数长度向量,例如 [5,8,4,6,7] 我想要 4,5 和 6 的“下”中值和 6,7 和 8 的“上”中值(6 是两个计算),对于偶数长度向量,例如 [5,8,4,6,7,9] 我想要 4,5 和 6 的“下”中值和 7,8 的“上”中值和 9. 我也在尝试使用一种快速的方法来做到这一点,并希望使用我已经改编并用于直接中位数计算的代码:-

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;
}

我可以将输入向量“拆分”成理论上的两半

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

}

我的问题是我不确定将上述 * 注释中位数计算应用于输入向量的指定相关部分的语法。我也许应该提一下,输入是一个 Octave ColumnVector input = args(0).column_vector_value() 并且长度在 10 到 50 个值之间。

【问题讨论】:

    标签: c++ octave median nth-element


    【解决方案1】:

    如果 input.length() 返回的 int 比你应该写的要多

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

    整数值总是在 c 中使用整数数学

    【讨论】:

      猜你喜欢
      • 2017-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      相关资源
      最近更新 更多