我正在尝试使用二进制集创建上三角矩阵:
我创建了所有可能的n x n二进制矩阵,只有上三角形值(不包括对角线)。我可以为n = 3的情况做一个for循环。这是3 x 3矩阵,有2^3 = 8个置换。所以8个矩阵。当我做n = 4,5,6,...时,我得到了一个形状不匹配错误。不知道为什么for循环不会迭代。
请参见下面的代码示例:
n = 3
# Now we need to make permutation of binary upper_count tuples
# This will give 2^n sets of n binary values.
from itertools import *
t1 = list(product([0,1],repeat= n))
print(t1)
print('\n')
# Now we create 2^n matrices of size nxn:
for i in t1:
m1 = np.zeros((n,n))
indices = np.triu_indices_from(m1,1)
upper = m1[indices]
m1[indices] = i
print(m1)
print('\n')
给出以下所需输出:
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
[[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 0.]
[0. 0. 1.]
[0. 0. 0.]]
[[0. 0. 1.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 0. 1.]
[0. 0. 1.]
[0. 0. 0.]]
[[0. 1. 0.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 1. 0.]
[0. 0. 1.]
[0. 0. 0.]]
[[0. 1. 1.]
[0. 0. 0.]
[0. 0. 0.]]
[[0. 1. 1.]
[0. 0. 1.]
[0. 0. 0.]]
对于n = 4:
- 我得到以下错误*我错过了什么?
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1), (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0), (1, 1, 1, 1)]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-68-75f42bce2989> in <cell line: 8>()
12 upper = m1[indices]
13
---> 14 m1[indices] = i
15 print(m1)
16 print('\n')
ValueError: shape mismatch: value array of shape (4,) could not be broadcast to indexing result of shape (6,)
1条答案
按热度按时间nwsw7zdq1#
我的t1是错的。我没有数对。
更新代码:
预期结果