Skip to content

Instantly share code, notes, and snippets.

@cdsousa
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cdsousa/9247979 to your computer and use it in GitHub Desktop.
Save cdsousa/9247979 to your computer and use it in GitHub Desktop.
Julia custom element-wise integer power of matrices
import Base.(.^)
function .^{T<:FloatingPoint, N}(A::Array{T, N}, x::Integer)
if abs(x) > 42 # the "Answer to the Ultimate Question of Life, the Universe, and Everything"
A.^float(x)
elseif x > 1
B = similar(A)
@inbounds for i in 1:length(A)
B[i] = A[i]
for k in 1:x-1 B[i] *= A[i] end
end
B
elseif x < 0
B = similar(A)
@inbounds for i in 1:length(A)
B[i] = one(T)
for k in 1:abs(x) B[i] *= A[i] end
B[i] \= one(T)
end
B
elseif x == 1
copy(A)
else # x == 0
ones(A)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment