mardi 5 mai 2015

how to traverse an n-dimensional array with stride

I have an indexing issue that I am trying to solve. I have a n-dimensional array with known shape. I would like to traverse the array with a stride (possibly different in each dim).

With fixed dimensions, I would do this with nested for loops (small arrays) and increment by the stride:

std::vector<int> shape = {10, 10}; // h,w
int num_dim = shape.size();
std::vector<int> stride = {1,2};

for (int i = 0; i< shape[0]; i+=stride[0]} {
    for (int j = 0; j< shape[1]; j+=stride[1]} {
     //print flattened index (row major)
     printf("index: %d\n",i*shape[1]+j);
    }

}

But how would I do this with and n-dimensional array (flattened).

Aucun commentaire:

Enregistrer un commentaire