0

In the example below, it is as if Python does not discriminate between angle[u][v] and radius[u][v].

That is, from the first command in the for loop, an element of the angle array is evaluated. Then, from the second command in the for loop, the corresponding element of the radius array is evaluated. My problem is that this value for radius[v][u] gets then overwritten onto angle[v][u].

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
import matplotlib as mpl
import math

X = np.arange(0, 656, 1)
Y = np.arange(0, 667, 1)
X, Y = np.meshgrid(X, Y)
X = X - 243 + 0.0
Y = Y - 363 + 0.0

angle = X
radius = X

height = X.shape[0]
width = X.shape[1]

print width
print height

for v in xrange(height):
    for u in xrange(width):
        angle[v][u] = math.atan2(X[v][u],Y[v][u])
        radius[v][u] = math.sqrt(X[v][u]**2 + Y[v][u]**2)
print angle
print radius

What am I missing here?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Henri
  • 1
  • 1
  • Canonical duplicate: http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python – jonrsharpe Jun 25 '15 at 21:08
  • @jonrsharpe I'd say is related, but here the OP has not yet realized he wants to copy the object :) – fferri Jun 25 '15 at 21:09
  • @mescalinum the duplicate explains both the problem and the solution. Did you imagine this had *never* been covered? – jonrsharpe Jun 25 '15 at 21:11
  • then a better duplicate of this should exist – fferri Jun 25 '15 at 21:11
  • @mescalinum *"better"* how? Note that you can edit it if you think you can improve it, which is more useful than answering the same question yet again. – jonrsharpe Jun 25 '15 at 21:14

1 Answers1

0
angle = X
radius = X

angle and radius are references to the same object X. When you change one, you are changing X, and vice versa.

Have a look at this example, with X and Y:

>>> X = np.arange(0,2)
>>> Y = X
>>> X, Y
(array([0, 1]), array([0, 1]))
>>> X[0] = 5
>>> X, Y
(array([5, 1]), array([5, 1]))

You should copy X if you don't want this behavior.

>>> from copy import copy
>>> X = np.arange(0,2)
>>> Y = copy(X)
>>> X, Y
(array([0, 1]), array([0, 1]))
>>> X[0] = 5
>>> X, Y
(array([5, 1]), array([0, 1]))
fferri
  • 18,285
  • 5
  • 46
  • 95