gpt4 book ai didi

processing - Processing/Arduino中如何计算统计模式

转载 作者:行者123 更新时间:2023-12-03 21:27:26 30 4
gpt4 key购买 nike

我是一名设计老师,试图帮助学生应对编程挑战,所以我编码是为了好玩,但我不是专家。

她需要找到 mode (最常见的值)在使用耦合到 Arduino 的传感器的数据构建的数据集中,然后根据结果激活一些功能。

除了如何在 Arduino 中计算模式外,我们已经解决了大部分问题。我找到了帖子 Get the element with the highest occurrence in an array 解决了 JavaScript 中的问题,但我无法“移植”它。

最佳答案

我用过 HashMap替换 js {} 动态对象实例和 float ,但@weberik 的端口看起来更直接。

void setup() {
int numValues = 10;
float[] values = new float[numValues]; //Create an empty sample array
for(int i = 0 ; i < numValues ; i++) values[i] = random(0.0,100.0); //Populate it with random values.
println("mode: " + mode(values));
}

float mode(float[] source) {
if (source.length == 0)
return -1;
HashMap<Float,Integer> modeMap = new HashMap<Float,Integer>();
float result = source[0];
int maxCount = 1;
for (int i = 0; i < source.length; i++) {
float el = source[i];
if (modeMap.get(el) == null)
modeMap.put(el,1);
else
modeMap.put(el,modeMap.get(el)+1);
if (modeMap.get(el) > maxCount) {
result = el;
maxCount = modeMap.get(el);
}
}
return result;
}

你提到了传感器输入,所以我假设数据会被连续采样,所以值可以以一定的间隔存储,然后发送到模式处理。只是一个疯狂的猜测,但她不是想稍微平均/平滑传感器读数吗?如果是这样,她可以在 Arduino 的数组中缓存一些值(比如 10 个),并在每次添加新值时获取平均值:

int vals[10]; //Array to store caches values.

void setup() {
Serial.begin(9600);
for (int i=0 ; i < 10 ; i++)
vals[i] = 0; //Init with zeroes
}

void loop() {
delay(100);
int currentVal = average(analogRead(0));
//Serial.print(currentVal,BYTE);
Serial.println(currentVal);
}

int average(int newVal) {
int total = 0; //Used to store the addition of all currently cached values
for(int i = 9; i > 0; i--) { //Loop backwards from the one before last to 0
vals[i] = vals[i-1]; //Overwrite the prev. value with the current(shift values in array by 1)
total += vals[i]; //Add to total
}
vals[0] = newVal; //Add the newest value at the start of the array
total += vals[0]; //Add that to the total as well
return total *= .1; //Get the average (for 10 elemnts) same as total /= 10, but multiplication is faster than division.
}

关于processing - Processing/Arduino中如何计算统计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7896329/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com