When I print my arr value i get the correct values for my 2D array but when I exit the while loop my values are all wrong.
I am not sure what i am doing wrong.
#num runs
n = 4
x = np.linspace(-1,1,n)
y = np.linspace(-1,1,n)
x1,y1 = np.meshgrid(x, y)
l = np.linspace(0,1000,n)
x = np.linspace(-1,1,n)
p1,p2 = np.meshgrid(l,l)
w020 = 5*(y1**2+x1**2)
row, cols = (n,n)
arr = [[0]*cols]*row
i = 0
p = 0
while i < n:
i += 1
p=0
while p < n:
arr[i-1][p] = 2+2*math.cos(2*math.pi*w020[i-1,p])
p += 1
print(arr)
The way you created the 2D array, creates a shallow list
Instead, if you want to update the elements of the list, you should use
Explanation:
One can create a list using :
or
In the first case all the indices of the array point to the same integer object
and when you assign a value to a particular index, a new int object is created, for eg
arr[4] = 5createsNow let us see what happens when we create a list of list, in this case, all the elements of our top list will point to the same list
And if you update the value of any index a new int object will be created. But since all the top-level list indexes are pointing at the same list, all the rows will look the same. And you will get the feeling that updating an element is updating all the elements in that column.
Credits: Thanks to Pranav Devarakonda for the easy explanation here