# Matrix with known entries but unknown size [closed]

I am trying to perform some calculations with a matrix that has let's say size N but unknown, please How can I write this in mathematica? The following function, along the lines of the suggestion by Guesswhoitis, produces what you appear to want.

m[r_] := SparseArray[{Band[{1, 1}] -> n, Band[{2, 1}] -> -2, Band[{1, 2}] -> -2}, {r, r}]


It is unclear whether the n in the picture is the same as n, the dimension of the matrix. (Do not use N, which is a reserved term.) If not, change Band[{1, 1}] -> n to Band[{1, 1}] -> whateveryouwant. As a sample result,

m // Normal
(* {{n, -2, 0, 0, 0}, {-2, n, -2, 0, 0}, {0, -2, n, -2, 0},
{0, 0, -2, n, -2}, {0, 0, 0, -2, n}} *)


Edit: In light of the OP's comment, I have changed the dimension to r while leaving the matrix diagonal elements n, now unspecified.

• Thank you for your answer. I misleaded you with the "N", the square matrix K is of size r x r ; with r arbitrary. I have a formulae that I want to compute: Formulae= V_transpose * K * V with V a vector of dimension "r" such that V=(1,0,0,..,0). – Zakariae Ben Slimane Jun 29 '15 at 10:39
• @Zakariae, that's just the element in the first row and first column, no? – J. M.'s technical difficulties Jun 29 '15 at 13:08
• It was the inverse of K, I typed the code below where there is an error In:= v[r_] := UnitVector[r, 1]; m[r_] := SparseArray[{Band[{1, 1}] -> n, Band[{2, 1}] -> -2, Band[{1, 2}] -> -2}, {r, r}]; Formulae[r_] := v[r].Inverse[m[r]].v[r]; Formulae Out= n/(n^2-4) In:= Formulae[Q] During evaluation of In:= SparseArray::adims: Array dimension specification {Q,Q} should be Automatic, a non-negative machine integer, or a list of non-negative machine integers. >> Out= UnitVector[Q,1].SparseArray[{Band[{1,1}]->n,Band[{2,1}]->-2,Band[{1,2}]->-2},{Q,Q}]^-1.UnitVector[Q,1] – Zakariae Ben Slimane Jun 30 '15 at 1:12

Assuming bbgodfrey's interpretation, I'd also expect this to be faster if dimension is large:

ToeplitzMatrix[PadRight[{#, -2}, #]] &


Though more memory hungry, it produces a packed array, so depending on what you're doing, it may have some performance benefits in use compared to a sparse realization (but the reverse could also be true, again, depends on what you're doing with it after creation).

Another approach is to use DiagonalMatrix and its optional third argument

n = 5;
mat[n_]:= DiagonalMatrix[ConstantArray[n, n]] +
DiagonalMatrix[ConstantArray[-2, n - 1], 1] +
DiagonalMatrix[ConstantArray[-2, n - 1], -1];