Interchanging between linear index and subscript is a very common requirement in image processing.
Especially in C++, this is regularly done because image arrays are allocated in a single one-dimensional chunks, but accessed by (row, column) subscripts.
MATLAB has neat functions for this interchange through 2 functions:
The code for these functions is fully visible to MATLAB licensees (by going to the source for these functions), but since MATLAB has array as a structure with array size information embedded inside – it is not trivial to transfer the code to C.
Also MATLAB has column-major storage of pixels while C uses row-major format. Figure 1 depicts the relation between linear index and subscripts in 2D image matrices, and shows how MATLAB and C differ in terms of row-major and column-major storage.
Hence I created a couplet of C/C++ functions which serve the same functions as the MATLAB functions – I named them (un-adventurously enough) ind2sub() and sub2ind(). The code is available in the files >>ind2sub.h<< and >>ind2sub.cpp<< in my bitbucket repository called UtilitiesCPP https://bitbucket.org/kritisen/utilitiescpp
Function help is available in the Doxygen generated manual – look in the folders called latex (look for refman.pdf) and html (look for index.html).