6

I am working with solving a linear system that becomes a tridiagonal matrix. In order to speed up the process for large matrices, I want to use sparse matrices. My problem is that the values are not constant along the bands, but change based on their horizontal position in the matrix (x position, if you will). For instance I want to do:

A = SparseArray[{Band[{1,1}]->func1[0,j], Band[{1,2}->func2[0,j], Band[{2,1}]->func3[0,j]},{10,10}];

where j indexes the x position. Is there a good way to do this?

Xpence
  • 63
  • 3

2 Answers2

7
func1[a_, b_] := a + b;
func2[a_, b_] := 1 + a + b;
func3[a_, b_] := a + 2 b;

n = 10;
sa = SparseArray[{Band[{1, 1}] -> (func1[0, #] & /@ Range[n]), 
    Band[{1, 2}] -> (func2[0, #] & /@ Range[n - 1]), 
    Band[{2, 1}] -> (func3[0, #] & /@ Range[n - 1])}, {n, n}];

sa // MatrixForm

Mathematica graphics

or

sa = Quiet@SparseArray[{Band[{1, 1}] -> (func1[0, #] & /@ Range[n]), 
    Band[{1, 2}] -> (func2[0, #] & /@ Range[n]), 
    Band[{2, 1}] -> (func3[0, #] & /@ Range[n])}, {n, n}];
sa // MatrixForm   

(* same result *)

kglr
  • 394,356
  • 18
  • 477
  • 896
1

another way.

Total@MapIndexed[
   DiagonalMatrix[SparseArray@#, #2[[1]] - 2] &,
    {func3[0, #] & /@ Range[n - 1],
     func1[0, #] & /@ Range[n],
     func2[0, #] & /@ Range[n - 1]}
   ] 

This might be faster than using Band (Even for this simple input , computing the vectors dominates the timing though )

george2079
  • 38,913
  • 1
  • 43
  • 110