# How can I dynamically allocate a matrix?

I am trying to allocate the following matrix in Mathematica. It has 1s where i=j, -1/2 in i-1,j and i+1,j. This is the code I am using to try to achieve this:

mat = ConstantArray[0, {10, 10}];
For[i = 1, i <= 10, i++,
For[j = 1, i <= 10, i++,
If[i == j, (mat[[i, j]] = 1;
mat[[i + 1, j]] = -1/2;
If[i > 1, mat[[i - 1, j]] = 1/2, 0]
), mat[[i, j]] = 0
]]];


However the output is not the desired: Can anyone tell me what I am missing? I need to do this for matrices of size 10x10, 50x50 and 100x100 so there is no way I am doing this by hand but I haven't been able to figure this out by my self.

Thank you.

• A somewhat esoteric way: NDSolveFiniteDifferenceDerivative[2, Range@12, "DifferenceOrder" -> 2]["DifferentiationMatrix"][[2 ;; 11, 2 ;; 11]]/-2 // Normal // MatrixForm Jul 14, 2020 at 3:50
• Esoteric indeed. Jul 14, 2020 at 3:54
• The reason your code did not work as expected is that you used i in the condition of the second For-loop instead of 'j': j = 1, i <= 10, i++, where it should be j = 1, j <= 10, j++. Jul 14, 2020 at 15:37

One of many ways:

mat = Normal@
SparseArray[{Band[{1, 1}] -> 1, Band[{1, 2}] -> -1/2,
Band[{2, 1}] -> -1/2}, {10, 10}];
mat // MatrixForm The Normal@ is not really necessary.

• Thanks a lot! I'l dig into the docs to see exactly how this works. This is so much better than using the for loops to fill the array. Jul 14, 2020 at 3:53
• @ÁngelCáceresLicona You're welcome! Other ways: (1) mat = Normal@SparseArray[{i_, j_} /; Abs[i - j] <= 1 :> (2 - 3 Abs[i - j])/2, {10, 10}] (2) ReplacePart[IdentityMatrix, {i_, j_} /; Abs[i - j] == 1 -> -1/2] (3) mat = IdentityMatrix + DiagonalMatrix[ConstantArray[-1/2, 9], 1] + DiagonalMatrix[ConstantArray[-1/2, 9], -1] Jul 14, 2020 at 3:55
Clear["Global*"]

A[n_Integer?Positive] :=
DiagonalMatrix[Table[1, n]] +
DiagonalMatrix[Table[-1/2, n - 1], 1, n] +
DiagonalMatrix[Table[-1/2, n - 1], -1, n];

A // MatrixForm 