# Code for the elementary $m\times m$ matrix $E_{ij}$

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.

• – AccidentalFourierTransform May 27 at 0:33
• 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}. – JimB May 27 at 1:09
• @JimB Thank you! It's getting late here but I eventually figured that out! – Mee Seong Im May 27 at 1:10
• 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. – bill s May 27 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


### Update

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.

Clear[eMatrix]
eMatrix[n_Integer?Positive][i_Integer, j_Integer] /; 0 < i <= n && 0 < j <= n :=
SparseArray[{{i, j} -> 1}, {n, n}]

• This is great. Thank you! (The way I would have done it would make my code unnecessarily complicated!) – Mee Seong Im May 27 at 1:54