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$ – J. M.'s ennui Oct 28 '12 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 '12 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$ – J. M.'s ennui Oct 28 '12 at 15:24
  • $\begingroup$ 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` $\endgroup$ – 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,


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, privacy policy and cookie policy

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