I have a loop structure which performs certain calculations and writes the results in some matrix $M$. When certain condition is satisfied the loop stops. Let's assume that this happens after $T$ iterations. Then, for the purposes of the problem I am considering, the necessary dimensions of $M$ are $d \times d$, where $d= \sum_{i=1}^{T+1} n^i$ and $n$ is a constant from the given problem considered (typically n=2,3,4). For example if $n=2$ and we know that the loop will finish after two iterations, we would have that $d=14$ and I would need a matrix $M$ that is $14\times 14$.
My issue is that since I do not know in advance when the loop is going to finish, I can not allocate in advance a size to the matrix $M$, so I have to assign something large to $d$ by guessing and hope the loop will finish before it runs out of space. I pre-allocate $M$ by:
M = ConstantArray[0, {d, d}]
So the question is, can I do this dynamically? In other words, can I increase the size of the matrix $M$ at each iteration without losing the previously written elements and how?
I can imagine that one could create a new matrix at each iteration of the appropriate size and copy the elements from previous iterations into it. Would that be efficient? How can it be done efficiently?
Thanks!