简体   繁体   中英

Accessing data in neighbor cells

I have a matrix M of size mxn which is saved as a one dimensional array N of length m * n . Every cell of this array contains some integer variables which are the ID of data points. The amount of integer variables in every cell changes over time.

N[0] = {1,4,5,7}
N[1] = {2,9,3,1,7,4}
N[2] = {7,1,3,9,8}
N[3] = {6,4,2}
...

I access these elements by using an index function which returns

idx = x + y * n

Given some index idx I want to use all integer variables of the neighbor cells and the central cell with index idx to access an array of data points D of size s . Size s can be very large.

To make my point clear: Instead of such a loop over all data points

for(int i=0; i<s; i++)
// Do something with D[i]

I want something like (but more compact)

// Access central cell
idx = x + y*n;
num_Elements = Number_of_Elements_Cell(x,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]

// Access right cell
idx = (x+1) + y*n;
num_Elements = Number_of_Elements_Cell(x+1,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]

// Access left cell
idx = (x-1) + y*n;
num_Elements = Number_of_Elements_Cell(x-1,y);
for(int i=0; i<num_Elements; i++)
// Do something with D[N[idx][i]]

and so on. For all cells I have to do that 9 times.

My question: Is there a better way to do that given the structure N ?

I'm not sure i understand your question well .... but you could try :

for (int i=-1 ; i <= 1 ; i++){
    for (int j = -1 ; j <=1 ; j++){
        idx = (x+i) + (y+j)*n;
        // Check if idx is not out of bounds
        num_Elements = Number_of_Elements_Cell(x+i,y+j);
        for(int k=0; k<num_Elements; k++)
             // Do something with D[N[idx][k]]
    }
}

Note that your index could very well be out-of-bounds which such a method, so you'll have to implement a test to prevent that.

That's the way to simply iterate on a cell and its 8 neighbors using a double for loop. If it's not what you expect, let me know, i'll edit/delete.

I'm not sure but maybe you're looking for something like this:

var distinctDataPoints = new List<int>();
for(int z = x - 1, z <= x + 1, z++)
{
    if(z < 0 || z > m)
        continue;

    for(int t = y-1, t <= y + 1, t++)
    {   
        if(t < 0 || t > n)
            continue;

        idx = z + t * n;

        for(int i = 0; i < num_Elements; i++)
        {
            if(!distinctDataPoints.Contains(N[idx][i])
                distinctDataPoints.Add(N[idx][i])
        }
    }
}

for(int dpIdx = 0; dpIdx < distinctDataPoints.Count; dpIdx++)
{
    //Do something with D[dpIdx]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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