Skip to content

Commit

Permalink
ndarray: implement fill and fill! (#297)
Browse files Browse the repository at this point in the history
It serve as an API corresponds to Python's `mx.nd.full()`
  • Loading branch information
iblislin authored and pluskid committed Oct 24, 2017
1 parent 15def2c commit 81b134f
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 0 deletions.
7 changes: 7 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@

* `deepcopy` for NDArray (#273)

* `fill` and `fill!` for NDArray (#TBD)
An API correspond to Python's `mx.nd.full()`

* `fill(x, dims, ctx=cpu())`
* `fill(x, dims...)`
* `fill!(x, arr::NDArray)`

## API Changes

* `reshape` of NDArray share the same interface with Base (#272).
Expand Down
25 changes: 25 additions & 0 deletions src/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,31 @@ function /(arg0 :: NDArray, arg :: Real)
end


"""
fill!(x, arr::NDArray)
Create an `NDArray` filled with the value `x`, like `Base.fill`.
"""
function fill!(x, arr::NDArray)
arr[:] = x
arr
end

"""
fill(x, dims, ctx=cpu())
fill(x, dims...)
Create an `NDArray` filled with the value `x`, like `Base.fill`.
"""
function fill{N}(x, dims::NTuple{N, Integer}, ctx::Context=cpu())
arr = empty(typeof(x), dims, ctx)
arr[:] = x
arr
end

fill(x, dims::Integer...) = fill(x, dims)


"""
Manipulating as Julia Arrays
----------------------------
Expand Down
37 changes: 37 additions & 0 deletions test/unittest/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,42 @@ function test_reshape()
@test size(C) == (50, 4)
end

function test_fill()
info("NDArray::fill")
thresh = 1e8

let x = mx.fill(42, 2, 3, 4)
@test eltype(x) == Int
@test size(x) == (2, 3, 4)
@test copy(x) == fill(42, 2, 3, 4)
end

let x = mx.fill(Float32(42), 2, 3, 4)
@test eltype(x) == Float32
@test size(x) == (2, 3, 4)
@test reldiff(copy(x), fill(Float32(42), 2, 3, 4)) < thresh
end

let x = mx.fill(42, (2, 3, 4))
@test eltype(x) == Int
@test size(x) == (2, 3, 4)
@test copy(x) == fill(42, 2, 3, 4)
end

let x = mx.fill(Float32(42), (2, 3, 4))
@test eltype(x) == Float32
@test size(x) == (2, 3, 4)
@test reldiff(copy(x), fill(Float32(42), 2, 3, 4)) < thresh
end

info("NDArray::fill!::arr")
let x = mx.fill!(42, mx.zeros(2, 3, 4))
@test eltype(x) == Float32
@test size(x) == (2, 3, 4)
@test reldiff(copy(x), fill(Float32(42), 2, 3, 4)) < thresh
end
end # function test_fill

function test_kwargs()
info("NDArray::kwargs")
dims1 = (2,3,4)
Expand Down Expand Up @@ -454,6 +490,7 @@ end
test_nd_as_jl()
test_dot()
test_reshape()
test_fill()
test_kwargs()
test_show()
end
Expand Down

0 comments on commit 81b134f

Please sign in to comment.