Skip to content

Commit

Permalink
Merge pull request #22256 from WillAyd/multi-index-iter-example
Browse files Browse the repository at this point in the history
DOC: Add C API Documentation for NPY_ITER_MULTI_INDEX
  • Loading branch information
seberg committed Sep 20, 2022
2 parents c3598cf + 2e58fd3 commit 2524a53
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions doc/source/reference/c-api/iterator.rst
Expand Up @@ -203,6 +203,66 @@ is used to control the memory layout of the allocated result, typically
}
Multi Index Tracking Example
----------------------------

This example shows you how to work with the :c:data:`NPY_ITER_MULTI_INDEX` flag. For simplicity, we assume the argument is a two-dimensional array.

.. code-block:: c
int PrintMultiIndex(PyArrayObject *arr) {
NpyIter *iter;
NpyIter_IterNextFunc *iternext;
npy_intp multi_index[2];
iter = NpyIter_New(
arr, NPY_ITER_READONLY | NPY_ITER_MULTI_INDEX | NPY_ITER_REFS_OK,
NPY_KEEPORDER, NPY_NO_CASTING, NULL);
if (iter == NULL) {
return -1;
}
if (NpyIter_GetNDim(iter) != 2) {
NpyIter_Deallocate(iter);
PyErr_SetString(PyExc_ValueError, "Array must be 2-D");
return -1;
}
if (NpyIter_GetIterSize(iter) != 0) {
iternext = NpyIter_GetIterNext(iter, NULL);
if (iternext == NULL) {
NpyIter_Deallocate(iter);
return -1;
}
NpyIter_GetMultiIndexFunc *get_multi_index =
NpyIter_GetGetMultiIndex(iter, NULL);
if (get_multi_index == NULL) {
NpyIter_Deallocate(iter);
return -1;
}
do {
get_multi_index(iter, multi_index);
printf("multi_index is [%" NPY_INTP_FMT ", %" NPY_INTP_FMT "]\n",
multi_index[0], multi_index[1]);
} while (iternext(iter));
}
if (!NpyIter_Deallocate(iter)) {
return -1;
}
return 0;
}
When called with a 2x3 array, the above example prints:

.. code-block:: sh
multi_index is [0, 0]
multi_index is [0, 1]
multi_index is [0, 2]
multi_index is [1, 0]
multi_index is [1, 1]
multi_index is [1, 2]
Iterator Data Types
---------------------

Expand Down

0 comments on commit 2524a53

Please sign in to comment.