Skip to content

Instantly share code, notes, and snippets.

@cossio
Created May 4, 2020 14:30
Show Gist options
  • Save cossio/786cb0295eb866d23e7579f1dd70dcab to your computer and use it in GitHub Desktop.
Save cossio/786cb0295eb866d23e7579f1dd70dcab to your computer and use it in GitHub Desktop.
undropdims: type stable inverse of dropdims
function mix_dims(dims1, dims2, t)
if in(t[1], dims2)
return (1, mix_dims(dims1, Base.tail(dims2), Base.tail(t))...)
else
return (dims1[1], mix_dims(Base.tail(dims1), dims2, Base.tail(t))...)
end
end
function mix_dims(dims1, dims2, t::Tuple{})
return ()
end
@generated function ntup(::Val{N}) where N
return ntuple(i -> i, Val(N))
end
function undropdims(A::AbstractArray{T,N}; dims::NTuple{M,Int}=()) where {T,N,M}
newdims = mix_dims(size(A), dims, ntup(Val(N+M)))
return reshape(A, newdims)
end
a = [1 2 3; 4 5 6]
undropdims(a; dims= (1, 3))
@cossio
Copy link
Author

cossio commented May 4, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment