Changing content of an array via a function

Dear All,

I am trying to assign values to an array via an index shifting function for a particular reason, I was wondering if there is a way to achieve that in Julia. A simple example is

a = [1 2 3]
b = [0 0 0] # I want to assign the values of a into b
b_shift(i) = b[i+1] # this shifts the index of b to a zero based index
for i in 0:2
    b_shift(i) = a[i+1] 
    # of course, the straight forward way would be b[i+1] = a[i+1],
    # but I need a index shifter operation for my purpose
    println(b_shift(i)) # output is 1 2 3

println(b) # output is [0 0 0], so b did not change

Is there a way I can turn b=a via the b_shift function? Any tips will be appreciated!

Note that b_shift(i) = b[i+1] defines a function that takes the integer i and returns b[i+1]. But then in your for loop, you have b_shift(i) = a[i+1] which is simply just overwriting the function definition (I believe you this is assigning the value of a[i+1] to the b shifted vector… its not). In order for you to do what you are doing, you’ll need some more machinery by overloading setindex and getindex functions.

If you want to use a 0-based vector, the best solution would be to use the package OffsetArrays.

using OffsetArrays
a = [1 2 3]
b = [0 0 0] # I want to assign the values of a into b

# create the offsets  -- note these are by reference. so modifying a_offset also modifies a
a_offset = OffsetArray(a, 0:2) 
b_offset = OffsetArray(b, 0:2) 
for i in 0:2
    b_offset[i] = a_offset[i] # will modify the original `b` as well.  

Thanks so much, @affans, your solution works great for my purpose!