3
$\begingroup$

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?

This is the matrix in question

$\endgroup$
7
$\begingroup$

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[5] // 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.

| improve this answer | |
$\endgroup$
  • $\begingroup$ 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). $\endgroup$ – Zakariae Ben Slimane Jun 29 '15 at 10:39
  • 1
    $\begingroup$ @Zakariae, that's just the element in the first row and first column, no? $\endgroup$ – J. M.'s technical difficulties Jun 29 '15 at 13:08
  • $\begingroup$ It was the inverse of K, I typed the code below where there is an error In[45]:= 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[2] Out[48]= n/(n^2-4) In[49]:= Formulae[Q] During evaluation of In[49]:= SparseArray::adims: Array dimension specification {Q,Q} should be Automatic, a non-negative machine integer, or a list of non-negative machine integers. >> Out[49]= UnitVector[Q,1].SparseArray[{Band[{1,1}]->n,Band[{2,1}]->-2,Band[{1,2}]->-2},{Q,Q}]^-1.UnitVector[Q,1] $\endgroup$ – Zakariae Ben Slimane Jun 30 '15 at 1:12
2
$\begingroup$

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).

| improve this answer | |
$\endgroup$
2
$\begingroup$

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];
| improve this answer | |
$\endgroup$

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