【问题标题】:How to solve the problem of processing a matrix and combining values with a second matrix?如何解决处理矩阵并将值与第二个矩阵组合的问题?
【发布时间】:2021-03-15 20:25:00
【问题描述】:

我创建了一个遍历矩阵并将矩阵 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],)

然后我将函数应用于矩阵

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)

我的输出

    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

输出应该是:

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

输出:

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

这是正常工作的方式

谁能帮我解决这个错误?

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    改变这一行 for i in range(len(a[0])):

    for i in range(min(len(a[0]), len(a[:,0]))):
    

    ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多