@@ -663,17 +663,15 @@ end
663
663
end
664
664
end
665
665
666
- function diff (a:: AbstractVector )
667
- @assert ! has_offset_axes (a)
668
- [ a[i+ 1 ] - a[i] for i= 1 : length (a)- 1 ]
669
- end
666
+ diff (a:: AbstractVector ) = diff (a, dims= 1 )
670
667
671
668
"""
672
669
diff(A::AbstractVector)
673
- diff(A::AbstractMatrix ; dims::Integer)
670
+ diff(A::AbstractArray ; dims::Integer)
674
671
675
- Finite difference operator of matrix or vector `A`. If `A` is a matrix,
676
- specify the dimension over which to operate with the `dims` keyword argument.
672
+ Finite difference operator on a vector or a multidimensional array `A`. In the
673
+ latter case the dimension to operate on needs to be specified with the `dims`
674
+ keyword argument.
677
675
678
676
# Examples
679
677
```jldoctest
@@ -694,14 +692,15 @@ julia> diff(vec(a))
694
692
12
695
693
```
696
694
"""
697
- function diff (A:: AbstractMatrix ; dims:: Integer )
698
- if dims == 1
699
- [A[i+ 1 ,j] - A[i,j] for i= 1 : size (A,1 )- 1 , j= 1 : size (A,2 )]
700
- elseif dims == 2
701
- [A[i,j+ 1 ] - A[i,j] for i= 1 : size (A,1 ), j= 1 : size (A,2 )- 1 ]
702
- else
703
- throw (ArgumentError (" dimension must be 1 or 2, got $dims " ))
704
- end
695
+ function diff (a:: AbstractArray{T,N} ; dims:: Integer ) where {T,N}
696
+ has_offset_axes (a) && throw (ArgumentError (" offset axes unsupported" ))
697
+ 1 <= dims <= N || throw (ArgumentError (" dimension $dims out of range (1:$N )" ))
698
+
699
+ r = axes (a)
700
+ r0 = ntuple (i -> i == dims ? UnitRange (1 , last (r[i]) - 1 ) : UnitRange (r[i]), N)
701
+ r1 = ntuple (i -> i == dims ? UnitRange (2 , last (r[i])) : UnitRange (r[i]), N)
702
+
703
+ return view (a, r1... ) .- view (a, r0... )
705
704
end
706
705
707
706
# ## from abstractarray.jl
0 commit comments