5
$\begingroup$

I want to generate the following matrix for any n:

      Table[A[i, j], {i, 0, n}, {j, 0, n}];

Where,

      A ={{0,1,0},{0,0,2},{0,0,0}} when n=2;

      A={{0,1,0,0},{0,0,2,0},{0,0,0,3},{0,0,0,0}} when n=3;


      A={{0,1,0,0,0},{0,0,2,0,0},{0,0,0,3,0},{0,0,0,0,4},{0,0,0,0,0}} when n=4, and so on for any n.

Thanks

$\endgroup$

4 Answers 4

9
$\begingroup$
Clear["Global`*"]

A[n_Integer?Positive] := DiagonalMatrix[Range[n], 1, n + 1]

A /@ Range[2, 4]//Column

enter image description here

$\endgroup$
1
  • $\begingroup$ Many thanks Bob Hanlon. $\endgroup$
    – user62716
    Jun 23, 2020 at 15:18
8
$\begingroup$

You can also use SparseArray + Band:

ClearAll[sA]
sA[n_] := SparseArray[Band[{1, 2}, Automatic] -> Range@n, n + {1, 1}]

Examples:

sA /@ Range[2, 4] // Map[MatrixForm] // Row

enter image description here

$\endgroup$
6
$\begingroup$

The following approach is easily adapted to other cases. (But Bob Hanlon's answer is the right one for the original question.)

makeMat[n_] := With[{
   zeros = ConstantArray[0, {n, n}],
   rules = (Rule[{#, 1 + #}, #] &) /@ Range[n - 1]
   },
  ReplacePart[zeros, rules]]
$\endgroup$
1
  • 1
    $\begingroup$ Many thanks Alan. $\endgroup$
    – user62716
    Jun 23, 2020 at 15:18
2
$\begingroup$

I sometimes like using Module to define local functions (more precisely, local symbols with DownValues) to use the ridiculous generality Mathematica provides for such definitions:

ClearAll[specialMatrix];
specialMatrix[n_Integer?Positive] := specialMatrix[n] =
  Module[{a, between = Between[{0, n}]},
   a[i_Integer?between, j_Integer?between] /; j == i + 1 = i + 1;
   a[_Integer, _Integer] = 0;
   Table[a[i, j], {i, 0, n}, {j, 0, n}]]

specialMatrix[3]
(* {{0, 1, 0, 0}, {0, 0, 2, 0}, {0, 0, 0, 3}, {0, 0, 0, 0}} *)

specialMatrix[4]
(* {{0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 0, 0, 3, 0}, {0, 0, 0, 0, 4}, {0, 0, 0, 0, 0}} *)

The memoization in the definition of specialMatrix is optional but may be worthwhile if you repeatedly use specialMatrix to generate large matrices.

$\endgroup$
1
  • 1
    $\begingroup$ Many thanks Pillsy. $\endgroup$
    – user62716
    Jun 23, 2020 at 15:17

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.