I should have spelt out explicitly that using Table
is not suitable for computing recursive relations because when computing the i
th element of the array, it is not possible to refer back to the i-1
th element.
If you decide to use arrays (they're called lists in Mathematica) to do this computation, then Do
might be a little easier than While
. First the array would need to be pre-allocated, as in
arr = ConstantArray[0, {10, 10}];
Then fill it up as
Do[arr[[i, j]] = ... , {i,1,10}, {j,1,10}]
Notice that arrays are indexed using [[...]]
, not [...]
.
However, what I showed you with the Fibonacci example is probably more suitable for this type of calculation than arrays. In the end it will easier to manage, but it does have a learning curve.
You also asked about returning 0 for all negative indices. This is not possible with arrays, but it is possible with functions.
The Fibonacci example would be extended by adding this:
fib[n_ /; n < 0] = 0
or alternatively
fib[n_?Negative] = 0
In Mathematica a function can have multiple definitions for multiple argument patterns (e.g. fib
was defined separately for the input 0, 1, negative inputs, or arbitrary inputs). So issuing an additional definition doesn't clear the previous one. This is why it's necessary to use Clear
before redefining a function.