# 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. – J. M. Oct 28 '12 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}] – R. M. Oct 28 '12 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. – J. M. Oct 28 '12 at 15:24
Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Read the FAQs! 3) When you see good Q&A, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. ALSO, remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign – chris Oct 28 '12 at 15:34

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