Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix with given numbers in random places in python/numpy

I have an NxN matrix filled with zeros. Now I want to add to the matrix, say, n ones and m twos to random places. I.e. I want to create a matrix where there is some fixed amount of a given number at random places and possibly a fixed amount of some other given number in random places. How do I do this?

In Matlab I would do this by making a random permutation of the matrix indices with randperm() and then filling the n first indices given by randperm of the matrix with ones and m next with twos.

like image 306
Echows Avatar asked Nov 19 '25 03:11

Echows


1 Answers

You can use numpy.random.shuffle to randomly permute an array in-place.

>>> import numpy as np
>>> X = np.zeros(N * N)
>>> X[:n] = 1
>>> X[n:n+m] = 2
>>> np.random.shuffle(X)
>>> X = X.reshape((N, N))
like image 136
Fred Foo Avatar answered Nov 21 '25 17:11

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!