Ask Your Question
0

Copy vectors

asked 2012-10-19 09:25:33 +0200

Mathmon gravatar image

updated 2012-10-19 11:42:56 +0200

kcrisman gravatar image

Hello everyone,

I have the following problem: I have two vectors v = vector(QQ, [1,1]), w = vector(QQ, [3,3]). I want to copy the coefficients of w into v. I can't set v = w directly, beacuse v is used as a value in some dictionaries. I could loop over the list() of the vectors, but I was wondering if there is some better way to copy all of the entries.

Example from comment:

l = {1: v}; v.set(1,2) Now l == {1: (1, 2)}, but v = copy(w) does not change l

edit retag flag offensive close merge delete

3 Answers

Sort by ยป oldest newest most voted
0

answered 2012-10-19 12:16:38 +0200

kcrisman gravatar image

Responding to updated issue: To some extent this is a Python issue, even for lists. v = int(22); L= [v]; L; v= int(23); L gives 22 both times. v.set() works because you didn't actually change the reference the variable v has, if I understand correctly.

The following does what you want, and isn't quite the loop you mentioned, though it's close. I don't know if there is a way to avoid the Python thing (feature, really) above.

sage: for x in w.iteritems(): v.set(*x)
....:
edit flag offensive delete link more

Comments

Assignment by reference is definitely an intentional design decision in python.

benjaminfjones gravatar imagebenjaminfjones ( 2012-10-19 15:19:16 +0200 )edit
0

answered 2012-10-19 15:17:31 +0200

benjaminfjones gravatar image

Responding to @Mathmon's comment to @kcrisman's first (?) answer: that's because "v" is a reference (pointer) to a vector object somewhere in memory. The statement v = copy(w) creates a new vector in memory with a copy of ws content and then assigns v as a reference to that new vector.

In the dictionary, I[1] is another reference (to the location in memory of the value associated with the key 1. So, for example if you want to update the vector value in I you could do something like:

sage: I = { 1: vector(QQ, (1,2)) }
sage: a = I[1]
sage: a.set(0,3)
sage: I
{1: (3, 2)}

to reassign the reference I[1] use it's name (not a secondary reference to the same location):

sage: w = vector(QQ, (4,5))
sage: I[1] = copy(w)
sage: I
{1: (4, 5)}
edit flag offensive delete link more
0

answered 2012-10-19 09:34:39 +0200

kcrisman gravatar image

Do you need this?

sage: v = vector(QQ, [1,1])
sage: w = vector(QQ, [3,3])
sage: v; w
(1, 1)
(3, 3)
sage: v = copy(w)
sage: v; w
(3, 3)
(3, 3)
sage: w = 22
sage: v; w
(3, 3)
22
edit flag offensive delete link more

Comments

Well, as an example: l = {1: v}; v.set(1,2) Now l == {1: (1, 2)}, but v = copy(w) does not change l...

Mathmon gravatar imageMathmon ( 2012-10-19 09:41:31 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2012-10-19 09:25:33 +0200

Seen: 1,788 times

Last updated: Oct 19 '12