@@ -659,17 +659,15 @@ end
659659 end
660660end
661661
662- function diff (a:: AbstractVector )
663- @assert ! has_offset_axes (a)
664- [ a[i+ 1 ] - a[i] for i= 1 : length (a)- 1 ]
665- end
662+ diff (a:: AbstractVector ) = diff (a, dims= 1 )
666663
667664"""
668665 diff(A::AbstractVector)
669- diff(A::AbstractMatrix ; dims::Integer)
666+ diff(A::AbstractArray ; dims::Integer)
670667
671- Finite difference operator of matrix or vector `A`. If `A` is a matrix,
672- specify the dimension over which to operate with the `dims` keyword argument.
668+ Finite difference operator on a vector or a multidimensional array `A`. In the
669+ latter case the dimension to operate on needs to be specified with the `dims`
670+ keyword argument.
673671
674672# Examples
675673```jldoctest
@@ -690,14 +688,15 @@ julia> diff(vec(a))
690688 12
691689```
692690"""
693- function diff (A:: AbstractMatrix ; dims:: Integer )
694- if dims == 1
695- [A[i+ 1 ,j] - A[i,j] for i= 1 : size (A,1 )- 1 , j= 1 : size (A,2 )]
696- elseif dims == 2
697- [A[i,j+ 1 ] - A[i,j] for i= 1 : size (A,1 ), j= 1 : size (A,2 )- 1 ]
698- else
699- throw (ArgumentError (" dimension must be 1 or 2, got $dims " ))
700- end
691+ function diff (a:: AbstractArray{T,N} ; dims:: Integer ) where {T,N}
692+ has_offset_axes (a) && throw (ArgumentError (" offset axes unsupported" ))
693+ 1 <= dims <= N || throw (ArgumentError (" dimension $dims out of range (1:$N )" ))
694+
695+ r = axes (a)
696+ r0 = ntuple (i -> i == dims ? UnitRange (1 , last (r[i]) - 1 ) : UnitRange (r[i]), N)
697+ r1 = ntuple (i -> i == dims ? UnitRange (2 , last (r[i])) : UnitRange (r[i]), N)
698+
699+ return view (a, r1... ) .- view (a, r0... )
701700end
702701
703702# ## from abstractarray.jl
0 commit comments