6
$\begingroup$

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?

$\endgroup$
7
$\begingroup$
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 *)

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

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 )

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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