c - 在嵌入式 C 中查找最接近给定值的多维数组中的值

标签 c arrays embedded

我正在使用 C 编程语言开发带有微 Controller 和颜色传感器的嵌入式颜色传感应用。

目前,我有一个带有校准值的数组,看起来像这样 (每一行都是对不同事物的校准)

unsigned long calibrationValues[6][6]

value1 value2 value3 value4 value5 value6    
value1 value2 value3 value4 value5 value6
value1 value2 value3 value4 value5 value6
value1 value2 value3 value4 value5 value6
value1 value2 value3 value4 value5 value6
value1 value2 value3 value4 value5 value6

和另一个数组

unsigned long scannedValue[6]

包含六个已扫描以根据校准值进行分析的值

我知道我将如何检查该值是否存在于数组中,但这对于我想做的事情来说太具体了,因为扫描用于分析的值可能与精确校准值略有不同

所以,我的问题是:我如何在 calibrationValues 行中找到与扫描值值最接近的结果索引?

例子

(以下使用的值仅供引用)

calibrationValues[6][6]

0 - 100 250 325 650 700 830
1 - 5   12  15  35  50  90
2 - ...
...

scannedValue[6]
0 - 350
1 - 80
2 - ...
...

scannedValue[0] 最接近 calibrationValues[0][2]
scannedValue[1] 最接近 calibrationValues[1][5]
...
等等

我看过其他问题,特别是 this有疑问但不确定如何适配多维数组

最佳答案

假设这听起来很简单:

int i, j;
int results[6];
int minDiff, diff;

for (i = 0; i < 6; ++i)
{
    results[i] = 0; 
    minDiff = abs(scannedValue[i] - calibrationValues[i][0]);

    for (j = 1; j < 6; ++j)
    {
        diff = abs(scannedValue[i] - calibrationValues[i][j]);
        if (diff < minDiff)
        {
            minDiff = diff;
            results[i] = j;
        }
    }
}

results[] 数组将包含从 0 到 5 的最接近索引。

关于c - 在嵌入式 C 中查找最接近给定值的多维数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701074/

相关文章:

c - C 中的 sizeof 数组元素

c - 当用户输入不正确的值以避免程序崩溃时,C 中的数据验证

c - C 中的特殊 #define 选项

arrays - Julia 中的静态数组?

c - 避免堆栈溢出(C 中的迷宫生成器)

php - 通过另一个键和值在多维数组中查找值

javascript - Howler.js - 从数组/for 循环引用和触发文件

C, 是否可以将宏分配给结构变量?

c - ATSAM4s8b,如何等待 USB 设备连接

c++ - GCC C++ (ARM) 和指向结构字段的常量指针