# Tridiagonal matrix for any n

I'm pretty new to Mathematica and I need to figure out how to create a $n\times n$ tridiagonal matrix for any $n$. I don't have the slightest clue where to begin.

Edit: got this far, not sure how to set it to nxn

SparseArray[{Band[{1, 1}] -> x, Band[{2, 1}] -> y,  Band[{1, 2}] -> z}, {5, 5}]
// MatrixForm

• Look up SparseArray[] and Band[]. If you have more questions, edit your question to say where you're having trouble. If you figure it out on your own, you can answer your own question. Oct 28, 2012 at 15:11
• Re: your edit, you will need to provide an integer as the matrix dimension. However, you can write it up as a general function as: tridiag[n_Integer?Positive] := SparseArray[..., {n, n}]
– rm -rf
Oct 28, 2012 at 15:18
• As noted by rm, if you want to produce, say, the $10\times10$ version of your tridiagonal matrix, simply change the {5, 5} in your code to {10, 10}. As an additional note, if you read through the docs for Band[], you can either give a scalar or a list as the right hand side of a Band[{p, q}] -> (* stuff *) rule, which might be useful for your needs. Oct 28, 2012 at 15:24

Following up on rm's suggestion, and particularly useful if you're going to be creating many such matrices, would be to define a function. For instance

 sparseMat[n_, {x_, y_,z_}] := SparseArray[{Band[{1, 1}] -> x, Band[{2, 1}] -> y,Band[{1, 2}] -> z}, {n, n}]


creates an $n$-by-$n$ tridiagonal matrix with (tri)diagonal elements $x$, $y$, and $z$. So for instance,

 sparseMat[6,{x,y,z}]


is the general 6-by-6 form with variables $x$, $y$, and $z$. You can give them explicit values by replacing the calling list

 sparseMat[6,{1,2,3}]


You will need to use MatrixForm[] to see the results in normal matrix form, for instance,

 sparseMat[6,{1,2,3}]//MatrixForm