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
  • 1
    $\begingroup$ 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. $\endgroup$ Oct 28, 2012 at 15:11
  • 3
    $\begingroup$ 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}] $\endgroup$
    – rm -rf
    Oct 28, 2012 at 15:18
  • 1
    $\begingroup$ 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. $\endgroup$ Oct 28, 2012 at 15:24

1 Answer 1


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,


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


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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.