# Using sparse matrices when value depends on position

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?

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


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 *)

• @Xpence, my pleasure. Thank you for the accept. – kglr Jun 26 '17 at 15:20

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 )