Skip to content

Commit 8c718f1

Browse files
committed
generated ind2sub / sub2ind definitions
1 parent 1af9458 commit 8c718f1

File tree

1 file changed

+26
-11
lines changed

1 file changed

+26
-11
lines changed

base/abstractarray.jl

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1007,17 +1007,32 @@ function repmat(a::AbstractVector, m::Int)
10071007
return b
10081008
end
10091009

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+
meta = Expr(:meta,:inline)
1014+
ex = :(I[$M] - 1)
1015+
for i = M-1:-1:1
1016+
if i > N
1017+
ex = :(I[$i] - 1 + $ex)
1018+
else
1019+
ex = :(I[$i] - 1 + dims[$i]*$ex)
1020+
end
1021+
end
1022+
Expr(:block, meta,:($ex + 1))
1023+
end
1024+
1025+
@generated function ind2sub{N}(dims::NTuple{N,Integer}, ind::Integer)
1026+
meta = Expr(:meta,:inline)
1027+
N==0 && return :($meta; ind==1 ? () : throw(BoundsError()))
1028+
exprs = Expr[:(ind = ind-1)]
1029+
for i = 1:N-1
1030+
push!(exprs,:(ind2 = div(ind,dims[$i])))
1031+
push!(exprs,Expr(:(=),symbol(:s,i),:(ind-dims[$i]*ind2+1)))
1032+
push!(exprs,:(ind=ind2))
1033+
end
1034+
push!(exprs,Expr(:(=),symbol(:s,N),:(ind+1)))
1035+
Expr(:block,meta,exprs...,Expr(:tuple,[symbol(:s,i) for i=1:N]...))
10211036
end
10221037

10231038
# TODO in v0.5: either deprecate line 1 or add line 2

0 commit comments

Comments
 (0)