Skip to content

Commit

Permalink
Generic zeros, ones, and eye, taking the desired array type as first …
Browse files Browse the repository at this point in the history
…argument
  • Loading branch information
martinholters committed Jun 13, 2016
1 parent deae75b commit defd6c9
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
21 changes: 21 additions & 0 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,27 @@ fill{T<:AbstractArray}(::Type{T}, v, dims::Dims) = fill!(fixate_eltype(T, typeof

zero{T}(x::AbstractArray{T}) = fill!(similar(x), zero(T))

for (fname, felt) in ((:zeros,:zero), (:ones,:one))
@eval begin
function ($fname){T<:AbstractArray}(::Type{T}, dims::Dims)
array_type=fixate_eltype(T,Float64)
fill(array_type, ($felt)(eltype(array_type)), dims)
end
($fname){T<:AbstractArray}(::Type{T}, dims::Integer...) = ($fname)(T, convert(Dims, dims))
($fname){T}(A::AbstractArray{T}) = fill!(similar(A), ($felt)(T))
end
end

function eye{T<:AbstractMatrix}(::Type{T}, m::Integer, n::Integer)
a = zeros(T,m,n)
for i = 1:min(m,n)
a[i,i] = one(eltype(a))
end
return a
end
eye{T<:AbstractMatrix}(::Type{T}, n::Integer) = eye(T, n, n)
eye{T<:AbstractMatrix}(::Type{T}, x::AbstractMatrix) = eye(T, size(x, 1), size(x, 2))

## iteration support for arrays by iterating over `eachindex` in the array ##
# Allows fast iteration by default for both LinearFast and LinearSlow arrays

Expand Down
11 changes: 2 additions & 9 deletions base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -167,19 +167,12 @@ for (fname, felt) in ((:zeros,:zero), (:ones,:one))
@eval begin
($fname)(T::Type, dims...) = fill!(Array{T}(dims...), ($felt)(T))
($fname)(dims...) = fill!(Array{Float64}(dims...), ($felt)(Float64))
($fname){T}(A::AbstractArray{T}) = fill!(similar(A), ($felt)(T))
end
end

function eye(T::Type, m::Integer, n::Integer)
a = zeros(T,m,n)
for i = 1:min(m,n)
a[i,i] = one(T)
end
return a
end
eye(m::Integer, n::Integer) = eye(Float64, m, n)
eye(T::Type, m::Integer, n::Integer) = eye(Matrix{T}, m, n)
eye(T::Type, n::Integer) = eye(T, n, n)
eye(m::Integer, n::Integer) = eye(Float64, m, n)
eye(n::Integer) = eye(Float64, n)
eye{T}(x::AbstractMatrix{T}) = eye(T, size(x, 1), size(x, 2))

Expand Down

0 comments on commit defd6c9

Please sign in to comment.