Create special Matrix in mathematica

Clear["Global`*"]

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

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

enter image description here


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


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]]

Tags:

Matrix