![](/img/trans.png)
[英]How to solve the problem of "ValueError: expected square matrix"?
[英]How to solve the problem of processing a matrix and combining values with a second matrix?
我创建了一个 function 遍历矩阵并将矩阵 b 中的值分配给它们。 首先它传递第一行和最后一列,然后传递第二行和倒数第二列,从而传递整个数组。
import os
import sys
import numpy as np
import math
np.set_printoptions(threshold=sys.maxsize)
def matrix_assing(a, b):
output = []
for i in range(len(a[0])):
horizontal_values_to_assign = a[i][: len(a[i]) - i]
vertical_values_to_assing = a.T[-(i+1)][i+1:]
values_to_assign = np.append(horizontal_values_to_assign, vertical_values_to_assing,)
output += list(zip(values_to_assign, b[i:len(b) - i],))
return output
a = np.array([[11, 12, 13, 14,15,16,17],
[21, 22, 23, 24,25,26,27],
[31, 32, 33, 34,35,36,37]])
n 取数组中的水平列数 n=a.shape[1] b 取垂直行数 b=a.shape[0] 我通过这个固定的公式计算这个
helper=n-b+1
print(helper)
我将使用结果来修剪矩阵
a=np.delete(a, np.s_[helper:], axis=1)
b = np.array([100,200,300,400,500,600,700],)
然后我将 function 应用于矩阵
c=str(matrix_assing(a, b))
c=str(c).replace(")",'\n')
c=str(c).replace("]",'')
c=str(c).replace("[",'')
c=str(c).replace("(",'')
c=str(c).replace(",",'')
c=str(c).replace("\n ",'\n')
print(c)
我的 output
Traceback (most recent call last):
File "C:\Users\Pifko\dp\pigeon_hole2.py", line 112, in <module>
dev=str(matrix_assing(a, b))
File "C:\Users\Pifko\dp\pigeon_hole2.py", line 13, in matrix_assing
horizontalne = a[i][: len(a[i]) - i]
IndexError: index 3 is out of bounds for axis 0 with size 3
output 应该是:
11 100
12 200
13 300
14 400
15 500
25 600
35 700
21 200
22 300
23 400
24 500
34 600
31 300
32 400
33 500
如果矩阵有 4 行或更多行,它可以工作
例子
a = np.array([[11, 12, 13, 14,15,16,17],
[21, 22, 23, 24,25,26,27],
[31, 32, 33, 34,35,36,37],
[41, 42, 43, 44,45,46,47]])
output:
11 100
12 200
13 300
14 400
24 500
34 600
44 700
21 200
22 300
23 400
33 500
43 600
31 300
32 400
42 500
41 400
这就是它正常工作的方式
谁能帮我解决这个错误?
将此行for i in range(len(a[0])):
更改为
for i in range(min(len(a[0]), len(a[:,0]))):
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.