如何使用C中的条件测试从数组中删除某些元素? [英] How to remove certain elements from an array using a conditional test in C?
问题描述
我正在编写一个程序,该程序通过一个整数数组并计算stdev来识别数据中的异常值。在这里,我想创建一个新数组,其中删除了已识别的异常值,以便重新计算avg和stdev。有办法可以做到吗?
I am writing a program that goes through an array of ints and calculates stdev to identify outliers in the data. From here, I would like to create a new array with the identified outliers removed in order to recalculate the avg and stdev. Is there a way that I can do this?
推荐答案
有一个非常简单的解决方案,可以改变您的思维方式 if
语句(实际上并没有出现在for循环中……可能想解决这个问题)。
There is a pretty simple solution to the problem that involves switching your mindset in the if
statement (which isn't actually in a for loop it seems... might want to fix that).
float dataMinusOutliers[n];
int indexTracker = 0;
for (i=0; i<n; i++) {
if (data[i] >= (-2*stdevfinal) && data[i] <= (2*stdevfinal)) {
dataMinusOutliers[indexTracker] = data[i];
indexTracker += 1;
}
}
请注意,这并不是特别可扩展的, dataMinusOutliers
数组可能会有很多未使用的索引。您始终可以使用 indexTracker-1
来记录数组的实际大小,并创建另一个数组,将 dataMinusOutliers中的重要值复制到该数组中
。有没有可能是更优雅的解决方案?是。这项工作符合您的要求吗?是的。
Note that this isn't particularly scalable and that the dataMinusOutliers
array is going to potentially have quite a few unused indices. You can always use indexTracker - 1
to note how large the array actually is though, and create yet another array into which you copy the important values in dataMinusOutliers
. Is there likely a more elegant solution? Yes. Does this work given your requirements though? Yup.
这篇关于如何使用C中的条件测试从数组中删除某些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!