Let $E_{ij}$ be an $m\times m$ matrix with a $1$ in the $(i,j)$-entry and zero otherwise.

DiagonalMatrix[{1},j,m] will put a $1$ in the first row along the $j$-th super-diagonal in an $m\times m$ matrix, and $0$ elsewhere. That is, this is the code for $E_{1,j}$.

I'm trying to write a code for $E_{ij}$, so {1} in DiagonalMatrix should be replaced with the tuple {0,...,0,1,0,...,0} of length $m-j$, where we put the $1$ in the $i$-th $\textit{component}$.

Note that Mathematica treats the notation {0,...,0,1,0,...,0} as a column vector.

  • 2
    $\begingroup$ KroneckerDelta. $\endgroup$ – AccidentalFourierTransform May 27 '19 at 0:33
  • 1
    $\begingroup$ You need to remove the extra square brackets. In other words, replace Table[[KroneckerDelta[5, k]], {k, 5}] with Table[KroneckerDelta[5, k]], {k, 5}. $\endgroup$ – JimB May 27 '19 at 1:09
  • 1
    $\begingroup$ @JimB Thank you! It's getting late here but I eventually figured that out! $\endgroup$ – Mee Seong Im May 27 '19 at 1:10
  • 2
    $\begingroup$ To create a 5x5 array with a one at the {2,3} entry, use SparseArray[{{2, 3} -> 1, {5, 5} -> 0}]. To get the regular (non-sparse) form, use Normal. $\endgroup$ – bill s May 27 '19 at 1:30

Will this work for you?

eMatrix[n_Integer?Positive][i_Integer, j_Integer] /;0 < i <= n && 0 < j <= n :=
  Module[{m = ConstantArray[0, {n, n}]}, m[[i, j]] = 1; m]

For example, the following gives all $E_{ij}$ for dimensions 3 x 3.

With[{n = 3}, Table[eMatrix[n][i, j], {i, n}, {j, n}]] // MatrixForm



As bils s points out in a comment, it might be better to use sparse arrays, which will certainly give faster code in most cases and will automatically be converted to normal arrays when necessary.

The folling code produces the $E_{ij}$ as sparse arrays.

eMatrix[n_Integer?Positive][i_Integer, j_Integer] /; 0 < i <= n && 0 < j <= n :=
  SparseArray[{{i, j} -> 1}, {n, n}]
| improve this answer | |
  • 1
    $\begingroup$ This is great. Thank you! (The way I would have done it would make my code unnecessarily complicated!) $\endgroup$ – Mee Seong Im May 27 '19 at 1:54

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.