Ask Your Question

# 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, ....

Thanks in advance!

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

## Comments

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 16:52:06 +0200 )edit

## 2 Answers

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

## Comments

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 21:09:18 +0200 )edit

Thanks! "block_matrix" is a good idea.

( 2013-11-13 04:41:04 +0200 )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

## Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

## Stats

Asked: 2013-11-12 13:29:42 +0200

Seen: 1,942 times

Last updated: Nov 13 '13