Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random diagonal matrix

Tags:

python

numpy

I want to create a random diagonal matrix with size n such that each element in the diagonal entries has 50% chance of being -1 and 50% chance of being 1. Is there any advice 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 includes 0 as the value too. I only want -1 and 1, excluding 0.

like image 592
Jun Jang Avatar asked Mar 06 '26 11:03

Jun Jang


1 Answers

You can use np.random.choice to sample a vector

import numpy as np
n=100
vec=np.random.choice([-1,1],n)
mat=np.diag(vec)
like image 75
Dinesh Avatar answered Mar 08 '26 02:03

Dinesh