引用另一个矩阵后,仍然填充第一行numpy.ones [英] First row of numpy.ones is still populated after referencing another matrix

查看:85
本文介绍了引用另一个矩阵后,仍然填充第一行numpy.ones的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个矩阵"A",其值如下所示.在使用numpy.ones创建一个矩阵'B'并通过索引'i'行和'j'列将值从'A'分配给'B'之后,所得的'B'矩阵保留了第一行来自原始的"B"矩阵.我不确定为什么下面提供的代码会发生这种情况.

I have a matrix 'A' whose values are shown below. After creating a matrix 'B' of ones using numpy.ones and assigning the values from 'A' to 'B' by indexing 'i' rows and 'j' columns, the resulting 'B' matrix is retaining the first row of ones from the original 'B' matrix. I'm not sure why this is happening with the code provided below.

从命令行生成的"B"矩阵如下所示:

The resulting 'B' matrix from command line is shown below:

import numpy
import numpy as np


A = np.matrix([[8,8,8,7,7,6,8,2],
               [8,8,7,7,7,6,6,7],
               [1,8,8,7,7,6,6,6],
               [1,1,8,7,7,6,7,7],
               [1,1,1,1,8,7,7,6],
               [1,1,2,1,8,7,7,6],
               [2,2,2,1,1,8,7,7],
               [2,1,2,1,1,8,8,7]])


B = np.ones((8,8),dtype=np.int)

for i in np.arange(1,9):
    for j in np.arange(1,9):
        B[i:j] = A[i:j]

C = np.zeros((6,6),dtype=np.int)
print C

D = np.matrix([[1,1,2,3,3,2,2,1],
               [1,2,1,2,3,3,3,2],
               [1,1,2,1,1,2,2,3],
               [2,2,3,2,2,2,1,3],
               [1,2,2,3,2,3,1,3],
               [1,2,3,3,2,3,2,3],
               [1,2,2,3,2,3,1,2],
               [2,2,3,2,2,3,2,2]])
print D

for k in np.arange(2,8):
    for l in np.arange(2,8):


            B[k,l] # point in middle
            b = B[(k-1),(l-1)]
            if b == 8:
                # Matrix C is smaller than Matrix B
                C[(k-1),(l-1)] = C[(k-1),(l-1)] + 1*D[(k-1),(l-1)]

#Output for Matrix B
B=
        [1,1,1,1,1,1,1,1],
        [8,8,7,7,7,6,6,7],
        [1,8,8,7,7,6,6,6],
        [1,1,8,7,7,6,7,7],
        [1,1,1,1,8,7,7,6],
        [1,1,2,1,8,7,7,6],
        [2,2,2,1,1,8,7,7],
        [2,1,2,1,1,8,8,7]

推荐答案

Python从0开始计数,因此如果将np.arange(1,9)替换为np.arange(9)

Python starts counting at 0, so your code should work find if you replace np.arange(1,9) with np.arange(9)

In [11]: np.arange(1,9)
Out[11]: array([1, 2, 3, 4, 5, 6, 7, 8])

In [12]: np.arange(9)
Out[12]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])

这篇关于引用另一个矩阵后,仍然填充第一行numpy.ones的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆