Last active
December 17, 2015 23:49
-
-
Save johnmyleswhite/5691630 to your computer and use it in GitHub Desktop.
Combining Matlab's `repmat` with R's `rep` for tensors of arbitrary order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function repeat{T}(v::Array{T}, | |
dims::Integer...; | |
repetitions::Integer = 1) | |
n = length(v) | |
n_res = n * repetitions * prod(dims) | |
res = Array(T, tuple(repetitions * n * dims[1], dims[2:end]...)...) | |
for i in 0:(n_res - 1) | |
index = mod(fld(i, repetitions), n) | |
res[i + 1] = v[index + 1] | |
end | |
return res | |
end | |
myrepmat{T}(v::Vector{T}, a::Integer, b::Integer) = repeat(v, a, b) | |
myrepmat{T}(m::Matrix{T}, a::Integer, b::Integer) = repeat(m, a, b) | |
@assert isequal(repeat(["A", "B"], 1, repetitions = 1), | |
["A", "B"]) | |
@assert isequal(repeat(["A", "B"], 2, repetitions = 1), | |
["A", "B", "A", "B"]) | |
@assert isequal(repeat(["A", "B"], 1, repetitions = 2), | |
["A", "A", "B", "B"]) | |
@assert isequal(repeat(["A", "B"], 2, repetitions = 2), | |
["A", "A", "B", "B", "A", "A", "B", "B"]) | |
@assert isequal(repeat(["A", "B"], 1, 1, repetitions = 1), | |
["A", "B"]'') | |
@assert isequal(repeat(["A", "B"], 1, 2, repetitions = 1), | |
["A" "A"; | |
"B" "B"]) | |
@assert isequal(repeat(["A", "B"], 2, 1, repetitions = 1), | |
["A"; | |
"B"; | |
"A"; | |
"B";]'') | |
@assert isequal(repeat(["A", "B"], 2, 2, repetitions = 1), | |
["A" "A"; | |
"B" "B"; | |
"A" "A"; | |
"B" "B";]) | |
@assert isequal(repeat(["A", "B"], 2, 2, repetitions = 2), | |
["A" "A"; | |
"A" "A"; | |
"B" "B"; | |
"B" "B"; | |
"A" "A"; | |
"A" "A"; | |
"B" "B"; | |
"B" "B";]) | |
for i in 1:3 | |
for j in 1:3 | |
@assert isequal(myrepmat(["A", "B"], i, j), | |
repmat(["A", "B"], i, j)) | |
end | |
end | |
for i in 1:3 | |
for j in 1:3 | |
@assert isequal(myrepmat(["A", "B"]'', i, j), | |
repmat(["A", "B"]'', i, j)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Next set of ideas: