3
$\begingroup$

I would like to create the following sparse matrix

\begin{equation} 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}, \end{equation} 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$?

$\endgroup$
1
  • $\begingroup$ You may want to consider a[i] instead of ai. $\endgroup$
    – evanb
    Jan 17 at 10:27

2 Answers 2

4
$\begingroup$

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]

enter image description here

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

enter image description here

$\endgroup$
3
  • $\begingroup$ Great! Thank you very much. $\endgroup$
    – Shasa
    Jan 17 at 9:43
  • $\begingroup$ Look at the "Addendum" $\endgroup$ Jan 17 at 10:03
  • $\begingroup$ Thanks for the update. Replacing i-1 with n-i makes the matrix correct. $\endgroup$
    – Shasa
    Jan 17 at 10:09
4
$\begingroup$
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] 

enter image description here

$\endgroup$
1
  • $\begingroup$ ,(+1) thank you for your response. It is simpler than my script. $\endgroup$
    – Shasa
    Jan 17 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.