Mizzle
Mizzle

Reputation: 757

How to keep the value for a vector in Julia

I have two vectors vector1 and vector2 in Julia. Suppose vector1 = zeros(3). I set vector2 = vector1. Then I let vector2[1] = 1. vector2 will be [1, 0, 0]. However, vector1 will also be [1, 0, 0] automatically. I want to keep vector1 as [0, 0, 0].

In other words, after running

vector1 = zeros(3)
vector2 = vector1
vector2[1] = 1

I want vector1 still be zeros(3). Is there an easy way for me to do that?

Upvotes: 2

Views: 115

Answers (1)

Max Power
Max Power

Reputation: 8954

I don't have Julia installed so I can't check this but here's how I'd do this in Python, adapted for Julia syntax. Can you confirm this works?

vector1 = zeros(3)
vector2 = copy(vector1)
vector2[1] = 1

After a bit more reading, depending on what's in your array you might want to consider deepcopy instead of copy.

Upvotes: 3

Related Questions