通过平均减少数组大小
Reducing an array size by averaging
我有一个大的采样波形,我想通过将它重新采样(平均)到较低的速率来记录它的压缩版本以用于诊断。较低的利率将始终是原始利率的偶数。
例如:通过平均 8 个样本块将 32K 波形压缩为 4K 波形。
有没有简单的方法可以使用 Linq/IEnumerable
不是很纯粹的 Linq,但这样做就可以了:
int divisor = 2;
int index = 0;
var cutSamples = samples
.GroupBy(s => index++ / divisor)
.Select(g => g.Average());
在性能方面,Linq 不是你的朋友,所以这会快得多:
public static double[] CutSamples(double[] samples, int divisor)
{
var reducedSamples = new double[samples.Length / divisor];
int reducedIndex = 0;
for (int i = 0; i < samples.Length; i += divisor)
{
double sum = 0;
int count = 0;
for (int j = 0; j < divisor && (i + j) < samples.Length; j++)
{
sum += samples[i + j];
count++;
}
reducedSamples[reducedIndex++] = sum / count;
}
return reducedSamples;
}
我有一个大的采样波形,我想通过将它重新采样(平均)到较低的速率来记录它的压缩版本以用于诊断。较低的利率将始终是原始利率的偶数。 例如:通过平均 8 个样本块将 32K 波形压缩为 4K 波形。
有没有简单的方法可以使用 Linq/IEnumerable
不是很纯粹的 Linq,但这样做就可以了:
int divisor = 2;
int index = 0;
var cutSamples = samples
.GroupBy(s => index++ / divisor)
.Select(g => g.Average());
在性能方面,Linq 不是你的朋友,所以这会快得多:
public static double[] CutSamples(double[] samples, int divisor)
{
var reducedSamples = new double[samples.Length / divisor];
int reducedIndex = 0;
for (int i = 0; i < samples.Length; i += divisor)
{
double sum = 0;
int count = 0;
for (int j = 0; j < divisor && (i + j) < samples.Length; j++)
{
sum += samples[i + j];
count++;
}
reducedSamples[reducedIndex++] = sum / count;
}
return reducedSamples;
}