On Sat, Jul 4, 2009 at 10:29 AM, Minh Nguyen<[email protected]> wrote:
>
> Hi Alex,
>
> On Sat, Jul 4, 2009 at 6:07 PM, Alex<[email protected]> wrote:
>>
>> Hi,
>>
>> The following assignment behaves unexpectedly:
>>
>> a=matrix(2) #makes a zero matrix
>> b=a
>> b[0,1]=2
>>
>> One would expect a to stay zero, and only b to change to [0 2 0 0],
>> but a changes as well!
>
> That is expected, as it is a Python issue, not an issue with Sage. In
> the above code sample, both a and b refer to the same object. What you
> want is to make a copy of the object that a refers to.
>
>
>> Is there a way to leave a fixed when changing b?
>
> Yes. Use the command copy() or deepcopy(). In the following session, I
> make a copy of the matrix A. In this way, changing the copy doesn't
> affect the original object that A refers to.
>
> ----------------------------------------------------------------------
> | Sage Version 4.0.2, Release Date: 2009-06-18                       |
> | Type notebook() for the GUI, and license() for information.        |
> ----------------------------------------------------------------------
> sage: A = matrix(2)
> sage: B = copy(A)
> sage: A; B
>
> [0 0]
> [0 0]
>
> [0 0]
> [0 0]
> sage: B[0,1] = 2
> sage: A; B
>
> [0 0]
> [0 0]
>
> [0 2]
> [0 0]
>
>
>> If a and b were numbers, changing b does not change a as well, as one
>> would expect.
>
> Again, it's a feature of Python, not an issue with Sage per se.
> However, note this inconsistent behaviour:

The behavior below is not at all inconsistent with what you just
explained.  When you write "M=2" below you are not changing M, you are
making the variable M refer at a different object, namely 2.    That's
no different than writing "b=random_matrix(2)" in the above example,
then wondering why a didn't change.


> sage: M = 1
> sage: N = M
> sage: M; N
> 1
> 1
> sage: M = 2
> sage: M; N
> 2
> 1
>
> --
> Regards
> Minh Van Nguyen
>
> >
>



-- 
William Stein
Associate Professor of Mathematics
University of Washington
http://wstein.org

--~--~---------~--~----~------------~-------~--~----~
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/sage-support
URLs: http://www.sagemath.org
-~----------~----~----~----~------~----~------~--~---

Reply via email to