Python – Random diagonal matrix

Random diagonal matrix… here is a solution to the problem.

Random diagonal matrix

I want to create a random diagonal matrix of size n such that each element in the diagonal elements has a 50% probability of -1 and a 50% probability of 1. Any suggestions for this?

import numpy as np
diagonal_entries = np.random.randint(low = -1, high = 1, size = n)
D = np.diag(diagonal_entries)

However, the problem is that ‘np.random.randint also contains 0 as a value. I only want -1 and 1, not including 0.

Solution

You can sample vectors using np.random.choice

import numpy as np
n=100
vec=np.random.choice([-1,1],n)
mat=np.diag(vec)

Related Problems and Solutions