0

I have this problem in python. I have a function which take the following inputs

import numpy;
from numpy import *;
def GetInf(G, X, m, n):
    g           = G[m - 1, :].T;
    Y           = X;
    Y[m - 1, :] = 0;
    Y[:, n - 1] = 0;
    # Here I modify Y. The problem is that X is modified too. Why?
    # In fact, I add Y after I see that X is changing but X keeps changing.
    result      =  sum(Y * G);
    return result;

G = array([[1., 2., 3.], [4., 5., 6.]]);
X = array([[1., 0., 0.], [0., 0., 1.]]);
I = GetInf(G, X, 1, 1);

My problem is that when I debug the program I see that after modifying Y, X is also modified. I cannot understand why.

user199027
  • 95
  • 5
  • 4
    `Y` and `X` are names that point to the same object, if you want a copy do: `Y = X.copy()`. – Ashwini Chaudhary Jan 01 '15 at 18:04
  • you are assigning X to the Y variable. it is not the same as copying the matrix, but assigning the matrix object itself. so altering x is the same as altering y. try calling `Y = x.copy()` – Luis Masuelli Jan 01 '15 at 18:05
  • Here is a blog post explaining how variable assignment works in python. http://foobarnbaz.com/2012/07/08/understanding-python-variables/ – Dunes Jan 01 '15 at 18:09
  • Off-topic, but affectation doesn't mean what you think it does: *behaviour, speech, or writing that is pretentious and designed to impress.* – jonrsharpe Jan 01 '15 at 18:35

1 Answers1

2

it because of that you assign X to Y . that means Y is a reference to where X refer ! if you don't want that you have to make a copy of X :

Y=np.copy(X)
Mazdak
  • 105,000
  • 18
  • 159
  • 188