0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JuliaでNumPyのadd.atを再現してみる

Last updated at Posted at 2020-10-20

タイトルそのまま。

再現したいNumPyのコード

NumPyではin-placeな変更である。

Python(NumPy)

>>> A = np.ones((3,3))
>>> A
array([[1., 1., 1.],
       [1., 1., 1.],
       [1., 1., 1.]])
>>> B = np.array([[1, 1, 1], [2, 2, 2]])
>>> B
array([[1, 1, 1],
       [2, 2, 2]])
>>> np.add.at(A, [0, 2], B)
>>> A
array([[2., 2., 2.],
       [1., 1., 1.],
       [3., 3., 3.]])

Juliaのコード

+=演算子に.演算子を付加して.+=とし,ブロードキャストを行っていることに注意。
+=はブロードキャストを行わず,in-placeな変更ではない。
しかし,.+=では(当然)ブロードキャストを行うが,in-placeな変更である1

Julia

julia> A = ones(3,3)
3×3 Array{Float64,2}:
 1.0  1.0  1.0
 1.0  1.0  1.0
 1.0  1.0  1.0

julia> B = [1. 1. 1.; 2. 2. 2.]
2×3 Array{Float64,2}:
 1.0  1.0  1.0
 2.0  2.0  2.0

julia> selectdim(A, 1, [1, 3]) .+= B
2×3 view(::Array{Float64,2}, [1, 3], :) with eltype Float64:
 2.0  2.0  2.0
 3.0  3.0  3.0

julia> A
3×3 Array{Float64,2}:
 2.0  2.0  2.0
 1.0  1.0  1.0
 3.0  3.0  3.0

Sources

numpy.ufunc.at — NumPy v1.19 Manual
Arrays · The Julia Language
Multi-dimensional Arrays · The Julia Language
Mathematical Operations and Elementary Functions · The Julia Language

  1. http://web.eecs.umich.edu/~fessler/course/598/demo/pass-by-sharing.html

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?