Solution to the Covering Problem of Matrix Repeated Assignment in python

  • 2021-07-22 10:39:30
  • OfStack

In this paper, an example is given to solve the problem of repeated assignment coverage of matrix in python. Share it for your reference, as follows:


import itertools
import numpy as np
comb = list(itertools.combinations(list(range(regions)), 2))
bands_info = []
coeff = np.zeros([bands, len(comb)])
for cla in range(classes):
  class_info = data[:,cla*bands*regions:(cla+1)*bands*regions]
  for bs in range(bands):
    n = bs*regions
    for i in range(len(comb)):
      index1 = comb[i][0]+n
      index2 = comb[i][1]+n
      part1 = class_info[:, index1]
      part2 = class_info[:, index2]
      coeff[bs, i] = (np.corrcoef(part1, part2))[0, 1]
  bands_info.append(coeff.reshape([1,-1]))
coeff_info = np.vstack((bands_info[0], bands_info[1], bands_info[2],bands_info[3]))

For example, in this cyclic assignment process, the final result is that every matrix in bands_info is one. Why? I began to struggle here for a long time, and it was right to think about it. Later, I thought about the knowledge of C language I learned before, and I understood it a little. Originally, there are shallow copy and deep copy in python. If they are the same matrix, they occupy the same address. If they are assigned repeatedly in python, the previous values will be covered. Not only the current variable is overwritten, but also the variable you use later will be overwritten. For example, if the variable of a is overwritten by b, the value of a will become the value of b where you use the variable of a later. Isn't it terrible?

So how should it be modified?


import itertools
import numpy as np
comb = list(itertools.combinations(list(range(regions)), 2))
bands_info = []
for cla in range(classes):
  coeff = np.zeros([bands, len(comb)])
  class_info = data[:,cla*bands*regions:(cla+1)*bands*regions]
  for bs in range(bands):
    n = bs*regions
    for i in range(len(comb)):
      index1 = comb[i][0]+n
      index2 = comb[i][1]+n
      part1 = class_info[:, index1]
      part2 = class_info[:, index2]
      coeff[bs, i] = (np.corrcoef(part1, part2))[0, 1]
  bands_info.append(coeff.reshape([1,-1]))
coeff_info = np.vstack((bands_info[0], bands_info[1], bands_info[2],bands_info[3]))

Just change it to this. That is, the initial matrix is reset once in the loop, which means that a new address is given once, and then copied will not overwrite the previous results.

For more readers interested in Python related contents, please check the special topics of this site: "Summary of Python Mathematical Operation Skills", "Python Data Structure and Algorithm Tutorial", "Summary of Python Function Use Skills", "Summary of Python String Operation Skills" and "Introduction and Advanced Classic Tutorial of Python"

I hope this article is helpful to everyone's Python programming.


Related articles: