# How to generate a matrix of random values with zeros on the diagonal?

## Question:

I want get a matrix of random values with zero on main diagonal. Then the following codes work to integer values, but I actually want float value.

``````def matriz_custo(n):
numeros = sample(range(35,120+1),(n-1)*n)
c = np.array([numeros[i:i+n] for i in range(0,len(numeros),n)])
np.fill_diagonal(c, 0)
c[0][n-1] = 0
return (c)
``````

so I tried:

``````def matriz_custo_new(n):
numeros = np.random.uniform(low=27.32, high=37.25, size=(n-1,n))
c = np.array([numeros[i:i+n] for i in range(0,len(numeros),n)])
r = np.arange(n-1)
c[:,r,r] = np.inf
c[0][n-1] = 0
return (c)
``````

then happen to create a extra dimension. I want to access it like c[0][0], otherwise I have to change all of my code.

[EDIT]

I get it now! :

``````    def matriz_custo_new(n):
numeros = np.random.uniform(low=27.32, high=37.25, size=((n-1)*n,))
c = np.array([numeros[i:i+n] for i in range(0,len(numeros),n)])
r = np.arange(n-1)
c[r,r] = 0
c[0][n-1] = 0
return (c)
``````

``````def custom_matrix(low, high, n):
array = np.random.uniform(low, high, (n, n))
for i in range(n):
array[i][i] = 0
return array

custom_matrix(0, 1, 3)

# returns
# [[0.         0.56331153 0.09965334]
# [0.10010369 0.         0.79204369]
# [0.66917184 0.67228158 0.        ]]
``````

The `fill_diagonal` function in the NumPy package you’re using will allow you to fill the diagonal of any array regardless of its dimension.

``````import numpy as np

# Generates a 5x5 matrix/nested list of random float values
matrix = np.random.rand(5, 5)

# Sets diagonal values to zero
np.fill_diagonal(matrix, 0)

print(matrix)

# Example Matrix
[[0.         0.50388405 0.62069521 0.93842045 0.75608882]
[0.35300814 0.         0.48357286 0.59268458 0.15213251]
[0.63591576 0.61143272 0.         0.91271144 0.53997033]
[0.01979816 0.66435396 0.03416005 0.         0.02524777]
[0.62694323 0.02307084 0.32458185 0.7663526  0.        ]]

# Accessing specific elements
matrix[1][3]
0.5926845768187102

``````

Documentation here on the functionality. Cheers!

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.