@@ -1007,17 +1007,30 @@ function repmat(a::AbstractVector, m::Int)
1007
1007
return b
1008
1008
end
1009
1009
1010
- sub2ind (dims:: Tuple{} ) = 1
1011
- sub2ind (dims:: Tuple{} ,I:: Integer... ) = sum (I) - length (I) + 1
1012
- sub2ind (dims:: Tuple{Integer,Vararg{Integer}} , i1:: Integer ) = i1
1013
- sub2ind (dims:: Tuple{Integer,Vararg{Integer}} , i1:: Integer , I:: Integer... ) = i1 + dims[1 ]* (sub2ind (tail (dims),I... )- 1 )
1014
-
1015
- ind2sub (dims:: Tuple{} , ind:: Integer ) = ind== 1 ? () : throw (BoundsError ())
1016
- ind2sub (dims:: Tuple{Integer} , ind:: Integer ) = (ind,)
1017
- function ind2sub (dims:: Tuple{Integer,Vararg{Integer}} , ind:: Integer )
1018
- @_inline_meta ()
1019
- ind2 = div (ind- 1 ,dims[1 ])+ 1
1020
- tuple (ind- dims[1 ]* (ind2- 1 ), ind2sub (tail (dims),ind2)... )
1010
+ sub2ind (dims:: Tuple{Vararg{Integer}} ) = 1
1011
+ sub2ind (dims:: Tuple{Vararg{Integer}} , I:: Integer... ) = _sub2ind (dims,I)
1012
+ @generated function _sub2ind {N,M} (dims:: NTuple{N,Integer} , I:: NTuple{M,Integer} )
1013
+ ex = :(I[$ M] - 1 )
1014
+ for i = M- 1 : - 1 : 1
1015
+ if i > N
1016
+ ex = :(I[$ i] - 1 + $ ex)
1017
+ else
1018
+ ex = :(I[$ i] - 1 + dims[$ i]* $ ex)
1019
+ end
1020
+ end
1021
+ return :($ ex + 1 )
1022
+ end
1023
+
1024
+ @generated function ind2sub {N} (dims:: NTuple{N,Integer} , ind:: Integer )
1025
+ N== 0 && return :(ind== 1 ? () : throw (BoundsError ()))
1026
+ exprs = Expr[:(ind = ind- 1 )]
1027
+ for i = 1 : N- 1
1028
+ push! (exprs,:(ind2 = div (ind,dims[$ i])))
1029
+ push! (exprs,Expr (:(= ),symbol (:s ,i),:(ind- dims[$ i]* ind2+ 1 )))
1030
+ push! (exprs,:(ind= ind2))
1031
+ end
1032
+ push! (exprs,Expr (:(= ),symbol (:s ,N),:(ind+ 1 )))
1033
+ Expr (:block ,exprs... ,Expr (:tuple ,[symbol (:s ,i) for i= 1 : N]. .. ))
1021
1034
end
1022
1035
1023
1036
# TODO in v0.5: either deprecate line 1 or add line 2
0 commit comments