Calculate n-order determinant (n>1):
$\left|\begin{array}{cccccccc}a & b & 0 & 0 & \cdots & 0 & 0 & 0 \\ 0 & a & b & 0 & \cdots & 0 & 0 & 0 \\ 0 & 0 & a & b & \cdots & 0 & 0 & 0 \\ \vdots & \vdots & \vdots & \vdots & & \vdots & \vdots & \vdots \\ 0 & 0 & 0 & 0 & \cdots & 0 & a & b \\ b & 0 & 0 & 0 & \cdots & 0 & 0 & a\end{array}\right|$
The result should be
$a^{n}+(-1)^{n+1} b^{n}$
I can use the MMA code to get this result:
Clear["Global`*"];
s[n_] := SparseArray[{{n, 1} -> b, {i_, j_} /; j - i == 1 ->
b, {i_, j_} /; j == i -> a}, {n, n}]
detmat[n_] := Det[s[n]]
tab = Table[detmat[i], {i, 2, 10}]
$\left\{a^{2}-b^{2}, a^{3}+b^{3}, a^{4}-b^{4}, a^{5}+b^{5}, a^{6}-b^{6}, a^{7}+b^{7}, a^{8}-b^{8}, a^{9}+b^{9}, a^{10}-b^{10}\right\}$
FindSequenceFunction[tab, n - 1]
$a^{n}+(-b)^{-1+n} b$
However, when I tried another method, I made a mistake. How should I modify this code?
Clear["Global`*"];
detNewMatrix[n_] :=
Det[Module[{i = 1, j = 1, mm = Array[m, {n, n}]},
For[i = 1, i <= n, i++,
For[j = 1, j <= n, j++,
If[j == i + 1, m[i, j] = b,
If [i == n && j == 1, m[i, j] = b,
If[i == j, m[i, j] = a, m[i, j] = 0]]]]]; mm]]
tab = Table[detNewMatrix[k], {k, 2, 10}]
$\left\{a^{2}-b^{2}, a^{3}-a b^{2}+b^{3}, a^{4}+a b^{3}-b^{4}, a^{5}-a b^{4}+b^{5}, a^{6}+a b^{5}-b^{6}, a^{7}-a b^{6}+b^{7}, a^{8}+a b^{7}-b^{8}, a^{9}-a b^{8}+b^{9}, a^{10}+a b^{9}-b^{10}\right\}$
I think there may be a "coverage" in the code. It is correct to directly calculate any determinant, but when listing together, only the first determinant is calculated correctly, and the subsequent determinants are calculated incorrectly. But I don't know what went wrong.
For
loop is an awkward way to set up the matrix. In any case the issue is thatm
is not localized and so retains a bunch of values from prior iterations. To avoid this you might start the code asModule[ {i = 1, j = 1, m, mm}, mm = Array[m, {n, n}];...
$\endgroup$