first time on stack overflow. I am very new to python and programming in general.
This particular function is supposed to take 3 matrices as inputs: two N x 1 matrices and an N x N matrix. Using one of the matrices, it is supposed to sort all values of 1 to the top, and all values of 0 to the bottom. This works fine. The N x N matrix is supposed to swap columns that correspond to the rows that were swapped in the N x 1 matrix: ie if rows 3 and 4 are swapped in the N x 1 matrix, then columns 3 and 4 need to be swapped in the N x N matrix.
The issue is that, in the inner for loop, it seems to be updating the values of the variables as soon as the k_bar matrix (N x N) is changed, which causes all columns to have the same value in every row by the end of the iterations. I have no idea how to stop this, or why it is doing it.
If I print out the values immediately before and after the lines k_bar[0][k, (i + 1)] = temp_left[0][k]
and k_bar[0][k, i] = temp_right[0][k]
as it loops through the inner for loop, it prints array([1, 4, 7]) array([2, 5, 8])
and then on the next iteration it prints array([1, 4, 7]) array([1, 5, 8])
and keeps going until both read array([1, 4, 7])
.
Any help is appreciated.
Here is my code:
import numpy as np
def reorder(r, k_bar, f):
import numpy as np
num_react = 0
for i in range(len(r)):
if r[i][0] == 0:
pass
else:
num_react += 1
consecutive_count = 0
while(consecutive_count != num_react):
for i in range(len(r) - 1):
if r[i][0] == 0:
temp_above = r[i][0]
temp_below = r[i + 1][0]
r[i][0] = temp_below
r[i + 1][0] = temp_above
temp_above2 = f[i][0]
temp_below2 = f[i + 1][0]
f[i][0] = temp_below2
f[i + 1][0] = temp_above2
temp_left = []
temp_left.append(k_bar[0][:, i])
temp_right = []
temp_right.append(k_bar[0][:, (i + 1)])
for k in range(len(r)):
k_bar[0][k, (i + 1)] = temp_left[0][k]
k_bar[0][k, i] = temp_right[0][k]
else:
consecutive_count += 1
if consecutive_count == len(r) and consecutive_count != num_react:
consecutive_count = 0
print(r)
print(k_bar)
print(f)
ke = []
fe = []
re = []
ke.append(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype = int))
fe.append(np.array([0], dtype = int))
fe.append(np.array([0], dtype = int))
fe.append(np.array([1], dtype = int))
re.append(np.array([0], dtype = int))
re.append(np.array([0], dtype = int))
re.append(np.array([1], dtype = int))
print(ke, fe, re)
reorder(re, ke, fe)
I figured it out. The temp_left and temp_right were being considered as the same list as k_bar. Used temp_left.append(k_bar[0][:, i].copy())
and it worked fine.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.