Wolfram Research

Function Repository Resource:

ZeroDiagonal

Source Notebook

Replace the diagonal of an arbitrary matrix with zeros

Contributed by: Szabolcs Horvat

ResourceFunction["ZeroDiagonal"][matrix]

replaces the diagonal of matrix with zeros.

Details and Options

The input must be a full matrix. Higher-dimensional arrays cannot be used.
The matrix elements may be any expression, symbolic or numeric.
If the matrix contains machine-precision elements, the diagonal will be filled with machine-precision zeros. Otherwise, exact zeros will be used.

Examples

Basic Examples

Zero the diagonal of a matrix:

In[1]:=
ResourceFunction["ZeroDiagonal"][( {
   {1, 2, 3},
   {4, 5, 6},
   {7, 8, 9}
  } )]
Out[1]=

Scope

Use on a sparse matrix:

In[2]:=
sa = SparseArray[{{1, 1} -> 2, {1, 2} -> 3, {4, 5} -> 4}]
Out[2]=
In[3]:=
ResourceFunction["ZeroDiagonal"][sa]
Out[3]=

Use on a non-square matrix with symbols:

In[4]:=
ResourceFunction["ZeroDiagonal"][( {
    {a, 2, a^2},
    {b, b^3, -1}
   } )] // MatrixForm
Out[4]=

Use on a machine-precision matrix:

In[5]:=
ResourceFunction["ZeroDiagonal"]@
  RandomReal[{-1, 1}, {5, 5}] // MatrixForm
Out[5]=

Applications

Create a random directed graph with no self-loops:

In[6]:=
AdjacencyGraph@
 ResourceFunction["ZeroDiagonal"]@RandomInteger[1, {5, 5}]
Out[6]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information