Julia: Get range (minimum / maximum values) of a multidimensional array along specific axes

2.3k Views Asked by At

Given some array with dimensions N1, N2, N3, is there any way in Julia to get the minimum and maximum (the range) of this multidimensional array for the different levels of a given axis?

For example, say we have an array my_array with size (10, 3, 100) (meaning N1 = 10, N2 = 3, N3 = 100 to keep consistency with the terminology used above). I want to get the minimum and maximum values for the three different 'levels' of N2. Basically, I want some more concise code that does the following:

N2_1_range = (minimum(my_array[:,1,:]), maximum(my_array[:,1,:])
N2_2_range = (minimum(my_array[:,2,:]), maximum(my_array[:,2,:])
N2_3_range = (minimum(my_array[:,3,:]), maximum(my_array[:,3,:])

So basically, you're getting the minimum (respectively, maximum) across the entire n-dimensional sub-array that's singled out by index operations like my_array[:,n,:], for each of the levels n of the desired dimension (in this case, dimension N2).

I want (nicer) code that will generalize this operation to any desired dimension N of any multi-dimensional array, basically storing the ranges for the different 'settings/levels' of that dimension.

2

There are 2 best solutions below

5
Nils Gudat On BEST ANSWER

You want extrema(my_array, dims = 1) (or 2, or 3), see the documentation for extrema.

You can then use mapslices to specify the dimensions in your call that should have colons:

julia> a = rand(1:10, 10, 3, 100);


julia> mapslices(extrema, a, dims = [1, 3])
1×3×1 Array{Tuple{Int64,Int64},3}:
[:, :, 1] =
 (1, 10)  (1, 10)  (1, 10)

Note that there is currently an open issue about the performance of extrema being worse than calling minimum and maximum here, so you might want to check whether this causes performance issues.

0
aramirezreyes On

Does eachslice work for you?

julia> a = rand(10,3,100)
julia> b = [extrema(c) for c in eachslice(a,dims=2)]
3-element Array{Tuple{Float64,Float64},1}:
 (0.00019926768773892434, 0.9978490630494796)
 (0.00035292069651315927, 0.9998983532542789)
 (0.00012135841634353106, 0.9997039922122202)