Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Why does in-place array assignment behave differently here?

$
0
0

@groovyda wrote:

Hi - I’m new to Julia, been playing around a bit. I’ve been struggling to understand the below. I have some code where I need to switch some values in an array. I get (surprisingly) different results if I use

w[3], w[2] = w[2], w[3]

vs. 
w_copy = copy(w)
w_copy[3], w_copy[2] = w_copy[2], w_copy[3]  # or w_copy[3], w_copy[2] = w[2], w[3]

Note this is being run in a large for loop, where w3 is being inititalised along with other similar arrays.

This seems to give the correct results:

for m1 in all_prefs, m2 in all_prefs, m3 in all_prefs, w1 in all_prefs, w2 in all_prefs, w3 in all_prefs
    w1_p1 = f([m1,m2,m3], [w1,w2,w3])[1] 
    w2_copy = copy(w2)
    w2_copy[2], w2_copy[3] = w2_copy[3], w2_copy[2]
    w1_p2 = f([m1,m2,m3], [w1,w2_copy,w3])[1] 

But the below gives different results, which doesn’t seem correct:

for m1 in all_prefs, m2 in all_prefs, m3 in all_prefs, w1 in all_prefs, w2 in all_prefs, w3 in all_prefs
    w1_p1 = f([m1,m2,m3], [w1,w2,w3])[1] 
    w2[2], w2[3] = w2[3], w2[2]
    w1_p2 = f([m1,m2,m3], [w1,w2,w3])[1] 

Why should this be? Please help

Posts: 17

Participants: 5

Read full topic


Viewing all articles
Browse latest Browse all 2795

Latest Images

Trending Articles



Latest Images