arrayfire / arrayfire-python

Python bindings for ArrayFire: A general purpose GPU library.

Home Page:https://arrayfire.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Regarding reassignment of values in array

shyams2 opened this issue · comments

Consider the following segment of code:

a = af.to_array(np.arange(25).reshape(5,5))
b = af.Array([0, 1, 2, 3, 4, 0, 1, 2])
c = af.Array([0, 0, 0, 0, 0, 1, 1, 1])
a[b, c] = 100
print(a)

This gives:

arrayfire.Array()
Type: long int
[5 5 1 1]
       100        100          2          3          4 
       100        100          7          8          9 
       100        100         12         13         14 
       100        100         17         18         19 
       100        100         22         23         24 

This seems to change all the values of the 2nd column. My intention was to only change the 1st, 2nd and 3rd rows of the 2nd column.

A similar code in Numpy:

a = np.arange(25).reshape(5,5)
b = np.array([0, 1, 2, 3, 4, 0, 1, 2])
c = np.array([0, 0, 0, 0, 0, 1, 1, 1])
a[b, c] = 100
print(a)

Gives the result as:

array([[100, 100,   2,   3,   4],
       [100, 100,   7,   8,   9],
       [100, 100,  12,  13,  14],
       [100,  16,  17,  18,  19],
       [100,  21,  22,  23,  24]])

How can I get this result using arrayfire?

There is no easy way to do this in arrayfire. arrayfire-python uses the indexing behavior of arrayfire rather than numpy.

You will need to index a[c * a.dims(0) + b] = 100

Ah OK! Thanks
Is there a faster way for me to tell python to access the flattened array? I'm currently doing this:

a = af.to_array(np.arange(25).reshape(5,5))
b = af.Array([0, 1, 2, 3, 4, 0, 1, 2])
c = af.Array([0, 0, 0, 0, 0, 1, 1, 1])
d = c*af.Array.dims(a)[0] + b 
a = af.flat(a)
a[d] = 100
a = af.moddims(a, 5, 5)

@ShyamSS-95 Is a[d] = 100 without flattening causing an issue ? I checked, this does not work.

@ShyamSS-95 while we are at it, can I also ask where you are getting b and c from ?

Is a[d] = 100 without flattening causing an issue ?

Yes. a[i] refers to the i-th row. So without flattening, doing a[d] = 100 results in all the values getting changed.

I'm getting the arrays which contain the indices from af.where. Earlier I used to do something like this:

zones       = af.where(x<=boundary)
row         = zones%(gridpoints)
col         = zones/(gridpoints) 
f[row, col] = 0 

Earlier, I was under the assumption that I would have to pass the address in terms of row and column indices. Now, I guess I can perform the reassignment operation directly using the values returned by af.where and passing it to the flattened array.

@ShyamSS-95 That's what I thougt :D

try f = af.select(x > boundary, f, 0) for these types of cases. Much simpler than what you are doing. Even numpy has an equivalent function in np.where

@ShyamSS-95 The following also works:

f = (x > boundary) * f

Tried this out. Works like a charm! Thank you