Looking for algorithm to iterate over matrix
The classical recursive algorithm to calculate the Cartesian product $A_1 \times \cdots \times A_n$ goes as follows:


If $n = 0$, return the empty tuple.
Otherwise, for every $x_1 \in A_1$ and $(x_2,\ldots,x_n) \in A_2 \times \cdots \times A_n$, output $(x_1,x_2,\ldots,x_n)$.


In the second step, you compute $A_2 \times \cdots \times A_n$ recursively.

You can convert this into an iterative algorithm. Suppose that $|A_i| = m_i$, and that the individual elements are $a_{ij}$. We count from $0$ to $m_1 \cdots m_n - 1$, and interpret each of these numbers as a mixed base number, involving the bases $m_1,\ldots,m_n$. We then convert the number into a tuple.

An alternative presentation of the iterative approach uses $n$ counters $c_1,\ldots,c_n$ counting from $0$ to $m_i-1$; when a counter reaches $m_i$, we reset it and all following counters to zero, and update the tuple accordingly.

Details of all these approaches left to you.