# Is there a way to "enumerate" `mapslices` other than```i = 0result = mapslices(m

Is there a way to “enumerate” `mapslices` other than

``````i = 0
result = mapslices(myarray; dims=dims) do x
i += 1
myfunction(x, i)
end
``````

?

Note that the original poster on Slack cannot see your response here on Discourse. Consider transcribing the appropriate answer back to Slack, or pinging the poster here on Discourse so they can follow this thread.
(Original message ) (More Info)

1 Like

(I’m the OP) I’m aware of `eachslice` but unfortunately I’m deliberately avoiding it, because `dims` in `eachslice` has the opposite meaning to that in `mapslices` (e.g. dims=1 <=> dims=2), and I want to follow the `mapslices` convention for other reasons.

Take a look at JuliennedArrays.jl:

``````julia> using JuliennedArrays

julia> v = rand(3,3,3);

julia> dims = (1, 2);

julia> result = map(enumerate(Slices(v, dims...))) do (i, v)
sum(v)^i
end
3-element Vector{Float64}:
3.1860188187847314
15.902106695465024
67.67688399859075
``````

This is several times faster - a factor of five for me:

``````map(enumerate(splitdimsview(v, 3))) do (i, v)
sum(v)^i
end
``````

That is:

``````using SplitApplyCombine, JuliennedArrays, BenchmarkTools

v = rand(100,100,100)

f_ja(v) = map(enumerate(Slices(v, 1, 2))) do (i, v)
sum(v)^i
end

f_sac(v) = map(enumerate(splitdimsview(v, 3))) do (i, v)
sum(v)^i
end

julia> @benchmark f_ja(\$v)
BenchmarkTools.Trial:
memory estimate:  1.69 KiB
allocs estimate:  22
--------------
minimum time:     1.614 ms (0.00% GC)
median time:      1.684 ms (0.00% GC)
mean time:        1.720 ms (0.00% GC)
maximum time:     6.179 ms (0.00% GC)
--------------
samples:          2906
evals/sample:     1

julia> @benchmark f_sac(\$v)
BenchmarkTools.Trial:
memory estimate:  896 bytes
allocs estimate:  1
--------------
minimum time:     324.384 μs (0.00% GC)
median time:      367.401 μs (0.00% GC)
mean time:        371.568 μs (0.00% GC)
maximum time:     928.039 μs (0.00% GC)
--------------
samples:          10000
evals/sample:     1

``````

But yes, different dims convention compared to mapslices.

1 Like