简体   繁体   English

在多维数组中查找最接近Embedded C中给定值的值

[英]Find a value within a multidimensional array that is closest to a given value in Embedded C

I am developing an embedded colour sensing application with a microcontroller and a colour sensor using the C programming language. 我正在使用C编程语言开发带有微控制器和颜色传感器的嵌入式颜色传感应用程序。

At the moment, I have an array with calibration values that looks something like this (Each row is a calibration for a different thing) 目前,我有一个带有校准值的数组,看起来像这样(每行是对另一件事的校准)

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

and another array 和另一个数组

unsigned long scannedValue[6]

that holds six values that have been scanned for analysis against the calibration values 包含六个已扫描以对照校准值进行分析的值

I know how I would check to see if the value exists within the array, but that is way too specific for what I would like to do as the value being scanned in for analysis could differ slightly to the exact calibrated value 我知道如何检查值是否存在于数组中,但这对于我想做的事情来说太具体了,因为要扫描的值用于分析可能会与准确的校准值略有不同

So, my question is: How would I find the index of the result in the calibrationValues row that is the closest to the scannedValue value? 因此,我的问题是:如何在最接近 scandValue值的CalibrationValues行中找到结果的索引?

Example

(values used below are just for example) (下面使用的值仅作为示例)

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] is closest to calibrationValues[0][2] ScandValue [0]最接近CalibrationValues [0] [2]
scannedValue[1] is closest to calibrationValues[1][5] ScandValue [1]最接近CalibrationValues [1] [5]
... ...
etc 等等

I have looked at other questions, in particular this question but not sure how to adapt to a multidimensional array 我看过其他问题,尤其是这个问题,但不确定如何适应多维数组

Assuming this is as straight forward as it sounds: 假设这听起来很简单:

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

The results[] array will contain the closest index from 0 to 5. results[]数组将包含0到5之间最接近的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM