First time here? Check out the FAQ!

Ask Your Question
0

create a tridiagonal matrix

asked 11 years ago

gundamlh gravatar image

updated 11 years ago

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

Preview: (hide)

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.

kcrisman gravatar imagekcrisman ( 11 years ago )

2 Answers

Sort by » oldest newest most voted
2

answered 11 years ago

Luca gravatar image

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]
Preview: (hide)
link

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.

kcrisman gravatar imagekcrisman ( 11 years ago )

Thanks! "block_matrix" is a good idea.

gundamlh gravatar imagegundamlh ( 11 years ago )
0

answered 11 years ago

gundamlh gravatar image

updated 11 years ago

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.

Preview: (hide)
link

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 11 years ago

Seen: 2,233 times

Last updated: Nov 13 '13