How to generate unique id from each element in matrix?

I'm coming from the programming world , and I need to create unique number for each element in a matrix. Say I have a $4\times4$ matrix $A$. I want to find a simple formula that will give each of the $16$ elements a unique number id. Can you suggest me where to start ?

How about $$f(r,c) = Kr+c,$$ where $K$ is the number of columns in the matrix and $r$ and $c$ correspond to the row and column you want an ID for?

For your 4 by 4 matrix, we would have $$f(r,c) = 4r+c,$$ where we have $r,c\in\{0,1,2,3\}$.

Any one-to-one mapping $\mathbb{N}^2 \to \mathbb{N}$ will work.

This one is easy $\mathbb{N}^2 \to \mathbb{N}$ bijection

Or this one is easier :-) If you have index $(i,j)$, your mapping will be $f(i,j)=2^i3^j$

Pairing Function :

Use pairing function . This is suggested by mathematicians to be the best way to generate a unique id , given 2 natural numbers (in our case say position in matrix) .

https://stackoverflow.com/questions/919612/mapping-two-integers-to-one-in-a-unique-and-deterministic-way

This can even be used for huge sized matrices

.

You can simply "string out" the elements of the matrix. That is, you label the $(1,1)$ entry with $1$, the $(1,2)$ entry with $2$, $\dots$, the $(2,1)$ entry with $5$, $\dots$, the $(4,4)$ entry with $16$.

You can construct such bijection $f:\mathbb{N}\to\mathbb{N}^2$ using the floor function that is contained in the standard libraries of most languages:

$$f(k)=\left(\left\lfloor\begin{matrix}k\\4\end{matrix}\right\rfloor,k-4\left\lfloor\begin{matrix}k\\4\end{matrix}\right\rfloor\right),\quad\quad f^{-1}((i,j))=4(i-1)+j.$$

If you're coming from a programming background, you should know about column-major and row-major orderings.

In row-major order, the matrix $\begin{pmatrix} 1 & 2 \\ 3 & 4 \end{pmatrix}$ is laid out in memory as [1, 2, 3, 4]. In column-major order, it is [1 3 2 4].

It should be easy to see how one can reverse the vector [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] into a matrix using row-major ordering (or column-major ordering--whichever!).