# create a tridiagonal matrix

In MATLAB, we can produce a tridiagonal matrix of order 2*m+1.

   matlab: m = 5;
matlab: diag(-m:m) + diag(ones(2*m,1),1) + diag(ones(2*m,1),-1)


In SAGE, do I have to write a function, two for-loops, or is there a convenient way? Perhaps it's already defined in one package, scipy/numpy, maxima, ....

define a my_function, here are two example codes

http://sage.math.canterbury.ac.nz/hom...

http://sage.math.canterbury.ac.nz/hom...

edit retag close merge delete

I don't think we have this built-in, but it would be a useful enhancement... I've opened http://trac.sagemath.org/ticket/15406 for the diag of the sort mentioned with offset.

( 2013-11-12 09:52:06 -0500 )edit

Sort by » oldest newest most voted

The diagonal matrix is an easy one:

sage: diagonal_matrix(range(-2,3))
[-2  0  0  0  0]
[ 0 -1  0  0  0]
[ 0  0  0  0  0]
[ 0  0  0  1  0]
[ 0  0  0  0  2]


The upper and lower diagonals are trickier. The best I could come up with is:

sage: block_matrix([[ 0, identity_matrix(4) ], [ zero_matrix(1,1), 0 ]])
[0|1 0 0 0]
[0|0 1 0 0]
[0|0 0 1 0]
[0|0 0 0 1]
[-+-------]
[0|0 0 0 0]
sage: block_matrix([[ 0, zero_matrix(1,1) ], [ identity_matrix(4), 0 ]])
[0 0 0 0|0]
[-------+-]
[1 0 0 0|0]
[0 1 0 0|0]
[0 0 1 0|0]
[0 0 0 1|0]

more

And diagonal_matrix(range(-2,3)) + block_matrix([[ 0, identity_matrix(4) ], [ zero_matrix(1,1), 0 ]]) + block_matrix([[ 0, zero_matrix(1,1) ], [ identity_matrix(4), 0 ]]) works, that is it doesn't print as block.

( 2013-11-12 14:09:18 -0500 )edit

Thanks! "block_matrix" is a good idea.

( 2013-11-12 21:41:04 -0500 )edit
sage: v = range(-2,6) # a list, arbitrarily given
sage: m = 3 # the off-diagonal index
sage: T = block_matrix([[zero_matrix(len(v),m), diagonal_matrix(v)],
[zero_matrix(m,m),0]])
sage: # len(v), get the length of the list to determine the dimensional of T
sage: T # result
[ 0  0  0|-2  0  0  0  0  0  0  0]
[ 0  0  0| 0 -1  0  0  0  0  0  0]
[ 0  0  0| 0  0  0  0  0  0  0  0]
[ 0  0  0| 0  0  0  1  0  0  0  0]
[ 0  0  0| 0  0  0  0  2  0  0  0]
[ 0  0  0| 0  0  0  0  0  3  0  0]
[ 0  0  0| 0  0  0  0  0  0  4  0]
[ 0  0  0| 0  0  0  0  0  0  0  5]
[--------+-----------------------]
[ 0  0  0| 0  0  0  0  0  0  0  0]
[ 0  0  0| 0  0  0  0  0  0  0  0]
[ 0  0  0| 0  0  0  0  0  0  0  0]


This is inspired by @Luca 's answer.

more