3
$\begingroup$

I am trying to allocate the following matrix in Mathematica.

Matrix a

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:

Output

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.

$\endgroup$
3
  • 4
    $\begingroup$ A somewhat esoteric way: NDSolve`FiniteDifferenceDerivative[2, Range@12, "DifferenceOrder" -> 2]["DifferentiationMatrix"][[2 ;; 11, 2 ;; 11]]/-2 // Normal // MatrixForm $\endgroup$
    – Michael E2
    Jul 14, 2020 at 3:50
  • $\begingroup$ Esoteric indeed. $\endgroup$
    – blidt
    Jul 14, 2020 at 3:54
  • $\begingroup$ 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++. $\endgroup$ Jul 14, 2020 at 15:37

2 Answers 2

5
$\begingroup$

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

Mathematica graphics

The Normal@ is not really necessary.

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$
    – blidt
    Jul 14, 2020 at 3:53
  • $\begingroup$ @Á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[10], {i_, j_} /; Abs[i - j] == 1 -> -1/2] (3) mat = IdentityMatrix[10] + DiagonalMatrix[ConstantArray[-1/2, 9], 1] + DiagonalMatrix[ConstantArray[-1/2, 9], -1] $\endgroup$
    – Michael E2
    Jul 14, 2020 at 3:55
4
$\begingroup$
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[5] // MatrixForm

enter image description here

$\endgroup$

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.