The purpose is to calculate the average value (AverageU) from a starting array (StartingU)
JavaScript
x
15
15
1
import numpy as np
2
3
AverageU=np.zeros((3,3))
4
StartingU=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
5
6
size=2
7
stride=1
8
m, n = StartingU.shape
9
10
print("Before averaging:")
11
print("AverageU=", AverageU)
12
print("StartingU=", StartingU)
13
14
AverageU = StartingU
15
The for loops that calculate the average values for AverageU
JavaScript
1
12
12
1
for i in range(0, m - size + 1, stride):
2
for j in range(0, n - size + 1, stride):
3
avg = np.sum(np.sum(AverageU[i:i + size, j:j + size])) / (size * size)
4
for ii in range(i, i + size):
5
for jj in range(j, j + size):
6
AverageU[ii, jj] = avg
7
#print("In for loop, StartingU=", StartingU)
8
9
print("After averaging:")
10
print("AverageU=", AverageU)
11
print("StartingU=", StartingU)
12
Output:
JavaScript
1
15
15
1
Before averaging:
2
AverageU= [[0. 0. 0.]
3
[0. 0. 0.]
4
[0. 0. 0.]]
5
StartingU= [[1 2 3]
6
[4 5 6]
7
[7 8 9]]
8
After averaging:
9
AverageU= [[3 3 3]
10
[5 5 5]
11
[5 5 5]]
12
StartingU= [[3 3 3]
13
[5 5 5]
14
[5 5 5]]
15
The problem is why StartingU gets updated? It should be unchanged
JavaScript
1
2
1
StartingU=np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2
Advertisement
Answer
AverageU changed since this code, not after for loop.
JavaScript
1
9
1
print("Before averaging:")
2
print("AverageU=", AverageU)
3
print("StartingU=", StartingU)
4
5
AverageU = StartingU # since here, AverageU variable changed
6
7
print("AverageU=", AverageU)
8
print("StartingU=", StartingU) # please check here again.
9
AverageU and StartingU are the same instances. You can check it with is function.
JavaScript
1
4
1
StartingU = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2
AverageU = StartingU
3
print(StartingU is AverageU) # True
4
You should make a new instance as the comment said.
JavaScript
1
7
1
StartingU = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
2
3
AverageU_new1 = StartingU[:]
4
AverageU_new2 = StartingU.copy()
5
print(StartingU is AverageU_new2) # False
6
print(StartingU is AverageU_new1) # False
7
AverageU = StartingU This code just makes another reference to the same object with a new name and this indicates the same memory. You can check the memory address of the variable with function id
You can compare like this.
JavaScript
1
5
1
copy_1 = StartingU
2
copy_2 = StartingU[:]
3
copy_3 = StartingU.copy()
4
print(id(StartingU), id(copy_1), id(copy_2), id(copy_3))
5
Notice
Copy with the colon is actually a shallow copy, it copies only the reference of the nested list.