Reputation: 25
I have just started using SAGE which is pretty close to python as I understand it, and I have come accross this problem where I'll have as a parameter of a function a matrix which I wish to use multiple times in the function with its same original function but through the different parts of the function it changes values.
I have seen in a tutorial that declaring a variable in the function as
variable = list(parameter)
doesnt affect the parameter or whatever is put in the parentheses. However I can't make it work..
Below is part of my program posing the problem (I can add the rest if necessary): I declare the variable determinant
which has as value the result of the function my_Gauss_determinant
with the variable auxmmatrix
as parameter. Through the function my_Gauss_determinant
the value of auxmmatrix
changes but for some reason the value of mmatrix
as well. How can avoid this and be able to re-use the parameter mmatrix
with its original value?
def my_Cramer_solve(mmatrix,bb):
auxmmatrix=list(mmatrix)
determinant=my_Gauss_determinant(auxmmatrix)
if determinant==0:
print
k=len(auxmmatrix)
solution=[]
for l in range(k):
auxmmatrix1=my_replace_column(list(mmatrix),l,bb)
determinant1=my_Gauss_determinant(auxmmatrix1)
solution.append(determinant1/determinant0)
return solution
Upvotes: 2
Views: 162
Reputation: 3453
If m
is a matrix, you can copy it into mm
by doing
sage: mm = m[:, :]
or
sage: mm = matrix(m)
To understand the need to copy container structures such as lists and matrices, you could read the tutorial on objects and classes in Python and Sage.
The other Sage tutorials are recommended too!
Upvotes: 0
Reputation: 37549
What you want is a copy of mmatrix
. The reason list(other_list)
works is because it iterates through every item in other_list
to create a new list. But the mutable objects within
the list aren't copied
>>> a = [{1,2}]
>>> b = list(a)
>>> b[0].add(7)
>>> a
[set([1,2,7])]
To make a complete copy, you can use copy.deepcopy
to make copies of the elements within the list
>>> import copy
>>> a = [{1,2}]
>>> b = copy.deepcopy(a)
>>> b[0].add(7)
>>> a
[set([1,2])]
So if you only want to copy the list, but don't want to copy the elements within the list, you would do this
auxmmatrix = copy.copy(matrix)
determinant = my_Gauss_determinant(copy.copy(matrix))
If you want to copy the elements within the list as well, use copy.deepcopy
Upvotes: 1