# How to generate a list of random NxN matrics with all diagonal elements are zero？

I'm trying to generate a list of random NxN matrics with all diagonal elements zero. I use the command

RM[n_, p_] := Table[RandomChoice[{p, 1 - p} -> {RandomReal[{-1, 1}], 0}], {j, 1, n}, {k, 1, n}]
N0 = Table[RM[50, 0.1], 100];


to generate the matrics and then write

For[i = 1, i <= 2, i++, N2 = N0[[i]] - Diagonal[N0[[i]]] // MatrixForm]


to make all parts in N0 have zeros on their diagonal. However, it doesn't work since Mathematica said the parts in N2 (except part1) do not exist.

• It depends very much from which distribution you're pulling the matrices. Nov 18, 2022 at 18:41
• Why should I avoid the For loop in Mathematica? Nov 18, 2022 at 18:42
• Hi there, the probability density is uniform. But I am still confused about how to generate it. I can find a single matrix with all zeros on the diagonal but cannot do it with a list, say a sample that contains 100 matrics. Nov 18, 2022 at 18:57
• How about N0 = Table[# - DiagonalMatrix@Diagonal@# &@RM[50, 0.1], 100];? This will subtract off the diagonal elements on the fly. Nov 18, 2022 at 19:24
• reply to March. Thanks for help. I tried the command and use diagonal[] to verify if it worked, but several numbers are remaining on the diagonal. Nov 18, 2022 at 20:21

\$Version

(* "13.1.0 for Mac OS X x86 (64-bit) (June 16, 2022)" *)

Clear["Global*"]

dim = 4;
nmat = 5;

SeedRandom[1234];


EDIT:

RM[n_Integer?(# > 1&), p_?(0 <= # <= 1 &)] :=
SparseArray[{{i_, j_} /; j != i :>
RandomChoice[{p, 1 - p} -> {RandomReal[{-1, 1}], 0}]},
{n, n}]

MatrixForm /@ (N0 = Table[RM[dim, 0.7], nmat])


• Thanks for your help! But there is another restriction that matrix-elements are 0 with probability 1-p, and with probability p are randomly drawn real numbers between 1 and -1. So only using RandomReal might not be enough? Nov 18, 2022 at 19:56
• Corrected randomizer Nov 18, 2022 at 20:34

If dim is the dimension and nmat the number of matrices in the list:

dim = 2;
nmat = 3
res = Table[t = RandomReal[{-1, 1}, {dim, dim}]; t - Diagonal[t], {nmat}] ;
MatrixForm /@ res


Here is a way to generate an n x n matrix with uniform random elements and a zero diagonal:

neb[z_] := ReplacePart[RandomVariate[UniformDistribution[1], {z, z}], {i_, i_} :> 0]

MatrixForm[neb[5]]


0 {0.927086} {0.632727} {0.794216} {0.111677}

{0.187628} 0 {0.859068} {0.496428} {0.901312}

{0.372348} {0.586887} 0 {0.686587} {0.83178}

{0.636274} {0.286791} {0.406237} 0 {0.167102}

{0.00708581} {0.89337} {0.126658} {0.108218} 0

• Unfortunately, you have a slight error. UniformDistribution[1] doesn't do what you guessed it does . UniformDistribution[] does what you need. (UniformDistribution[1]` generates a 1D list, rather than a single value). Nov 18, 2022 at 22:25