简体   繁体   English

在python / numpy中随机位置给定数字的矩阵

[英]Matrix with given numbers in random places in python/numpy

I have an NxN matrix filled with zeros. 我有一个用零填充的NxN矩阵。 Now I want to add to the matrix, say, n ones and m twos to random places. 现在我想添加到矩阵,比如n个和m两个到随机位置。 Ie 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. 在Matlab中,我会通过使用randperm()对矩阵索引进行随机排列,然后填充由矩阵的randperm给出的n个第一个索引,然后用两个填充m和m。

You can use numpy.random.shuffle to randomly permute an array in-place. 您可以使用numpy.random.shuffle随机随机置换数组。

>>> 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))

Would numpy.random.permutation be what you are looking for? numpy.random.permutation会成为你想要的吗?

You can do something like this: 你可以这样做:

In [9]: a=numpy.zeros(100)

In [10]: p=numpy.random.permutation(100)

In [11]: a[p[:10]]=1

In [12]: a[p[10:20]]=2

In [13]: a.reshape(10,10)
Out[13]: 
array([[ 0.,  1.,  0.,  0.,  0.,  2.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  2.,  0.],
       [ 0.,  2.,  0.,  0.,  0.,  0.,  2.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  2.,  0.,  2.,  1.,  1.,  0.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  2.,  0.,  0.,  0.],
       [ 0.,  2.,  0.,  2.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  2.,  0.,  0.,  0.,  1.,  0.]])

Here we create a random permutation, then set the first 10 indices taken from the permutation in a to 1, then the next 10 indices to 2. 在这里,我们创建一个随机排列,然后设置从置换中所采取的第一个10个指数a为1,那么在未来10个指数为2。

To generate the indices of the elements for where to add ones and twos, what about this? 要生成元素的索引以便在哪里添加一个和两个,那么这个呢?

# assuming N, n and m exist.
In [1]: import random
In [3]: indices = [(m, n) for m in range(N) for n in range(N)]
In [4]: random_indices = random.sample(indices, n + m)
In [5]: ones = random_indices[:n]
In [6]: twos = random_indices[n:]

Corrected as commented by Petr Viktorin in order not to have overlapping indexes in ones and twos . 校正为顺序的评论说:切赫Viktorin不要有重叠指标onestwos

An alternate way to generate the indices: 另一种生成索引的方法:

In [7]: import itertools
In [8]: indices = list(itertools.product(range(N), range(N)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM