# Creating a sparse matrix

I would like to create the following sparse matrix

$$$$A = \begin{pmatrix} a1+b1 t & k-1 & 0 & \ldots &0 \\ a2^{2}+b2^{2} t & a1+b1t & k-2 & \ldots &0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ ak-1^{k-1}+bk-1^{k-1} t & ak-2^{k-2}+bk-2^{k-2} t & ak-3^{k-3}+bk-3^{k-3} t & \ldots & 1\\ ak^{k}+bk^{k} t & ak-1^{k-1}+bk-1^{k-1} t & ak-2^{k-2}+bk-2^{k-2} t & \ldots & a1+b1t \\ \end{pmatrix},$$$$ where $$ai$$, $$bi$$ and $$t$$ are variables. My current script reads

mat[a_, b_, t_, n_] := Module[{tmp = 0, tmp2 = 0}, Do[
tmp = SparseArray[{Band[{m, 1}] -> a^m + b^m  t}, {n, n}];
tmp2 = tmp + tmp2;
, {m, 1, n}]; tmp2]


which keeps $$a^{i}+b^{i} t$$ on the $$i$$th lower diagonal of the matrix. How can I introduce variables ai and bi such that I ensure having $$ai^{i}+bi^{i} t$$ on these diagonals instead of $$a^{i}+b^{i} t$$?

• You may want to consider a[i] instead of ai. Commented Jan 17 at 10:27

## 2 Answers

Note that your current code does not create the element (k-i). To change a to ai and b to bi in your current script you can use "Symbol" like:

mat[a_, b_, t_, n_] :=
Module[{tmp = 0, tmp2 = 0},
Do[tmp =
SparseArray[{Band[{m, 1}] ->
Symbol["a" <> ToString[m]]^m +
Symbol["b" <> ToString[m]]^m   t}, {n, n}];
tmp2 = tmp + tmp2;, {m, 1, n}]; tmp2]


Addendum

To add he k-1 element:

mat[a_, b_, t_, n_] :=
Module[{tmp = 0, tmp2 = 0},
Do[tmp =
SparseArray[{Band[{m, 1}] ->
Symbol["a" <> ToString[m]]^m +
Symbol["b" <> ToString[m]]^m   t}, {n, n}];
tmp2 = tmp + tmp2;, {m, 1, n}];
tmp2 + SparseArray[{{i_, j_} /; j - i == 1 -> i - 1}, {n, n}]]

mat[a, b, t, 4] // MatrixForm


• Great! Thank you very much. Commented Jan 17 at 9:43
• Look at the "Addendum" Commented Jan 17 at 10:03
• Thanks for the update. Replacing i-1 with n-i makes the matrix correct. Commented Jan 17 at 10:09
sa[a_, b_, t_, n_] := SparseArray[Prepend[Band[{1, 2}] -> Range[0, n - 2]] @
Table[Band[{m, 1}] ->
Symbol["a"<>ToString[m]]^m + Symbol["b"<>ToString[m]]^m t,{m, n}],
{n, n}]

MatrixForm @ sa[a, b, t, 5]


• ,(+1) thank you for your response. It is simpler than my script. Commented Jan 17 at 10:29