Drop Julia array dimensions of length 1

Viewed 875

Say if I have a 5D Array with size 1024x1024x1x1x100. How can I make a new array that is 1024x1024x100?

The following works if you know which dimensions you want to keep ahead of time:

arr = arr[:, :, 1, 1, :]

But I don't know which dimensions are what size ahead of time and I would like to only keep dimensions given a boolean mask; something like this...

arr2 = arr[(size(arr) .> 1)]
1 Answers

The squeeze function was defined specifically for the purpose of removing dimensions of length 1. From the manual:

Base.squeeze — Function.

squeeze(A, dims)

Remove the dimensions specified by dims from array A. Elements of dims must be unique and within the range 1:ndims(A). size(A,i) must equal 1 for all i in dims.

To "squeeze" all the dimensions of size 1 (when they are unknown in advance), we need to find them and make them into a tuple. This is accomplished by ((size(arr).==1)...). So the result is:

squeeze(a,(find(size(a).==1)...))
Related