Systembolaget
Systembolaget

Reputation: 2514

Passing values from 2D array into a function

I have an array with 255 quadruples as shown below.

With each iteration of i I want to pass (correct terminology?) the first three values of each quadruple into a function (the three ? in getColourDistance below) in order to return the result of a calculation.

How must this be done in the C++ variant for Arduino?

Thanks!

const int SAMPLES[][4] ={{2223, 1612,  930,  10}, {1855,  814,  530,  20}, {1225,  463,  438,  30}, {1306,  504,  552,  40}, ...};

byte samplesCount = sizeof(SAMPLES) / sizeof(SAMPLES[0]);

for (byte i = 0; i < samplesCount; i++)
{
  tcs.getRawData(&r, &g, &b, &c);
  colourDistance = getColourDistance(r, g, b, ?, ?, ?);
  // do something based on the value of colourDistance
}

int getColourDistance(int sensorR, int sensorG, int sensorB, int sampleR, int sampleG, int sampleB)
{
  return sqrt(pow(sensorR - sampleR, 2) + pow(sensorG - sampleG, 2) + pow(sensorB - sampleB, 2));
}

Upvotes: 0

Views: 67

Answers (1)

parth_07
parth_07

Reputation: 1408

In this case array SAMPLES can be considered as a 2-dimensional array , thus SAMPLES[0][0] , will give the 1st element of 1st 1-dimensional array of SAMPLES , SAMPLES[0][1], will give the 2nd element of 1st 1-d array of SAMPLES , and so on , considering this terminology in mind we can do ,

#include <iostream>

const int SAMPLES[][4] = {{2223, 1612, 930, 10}, {1855, 814, 530, 20}, {1225, 463, 438, 30}, {1306, 504, 552, 40}, ...};

byte samplesCount = sizeof(SAMPLES) / sizeof(SAMPLES[0]);

for (byte i = 0; i < samplesCount; i++)
{
    //taking values of r,g,b as before    
    a=SAMPLES[i][0];//getting values of r,g,b 
    b=SAMPLES[i][1];//using the knowledge that SAMPLES[i][j]
    c=SAMPLES[i][2];//denotes jth element of ith 1-d array of SAMPLES
    colourDistance = getColourDistance(r, g, b, a, b, c);
}

Upvotes: 2

Related Questions