# How to transpose a 3d array?

Hi,

Is there an elegant way to transpose the first and second dimensions of a 3d array? For example, I’d like to go from an NxMxP array to an MxNxP array.

I’ve read the documentation etc., but can’t seem to extrapolate the 2d examples provided into a 3d format.

Cheers!

Try permutedims or permutedims!

2 Likes

Hey @Paulo_Jabardo, thanks for the solution! I tried two methods (Examples below) both return a vector of matrices. How do I convert that vector of matrices into a 3d array? Thanks!

``````#method 1
result1 = transpose.(array[:,:,i] for i = 1:11)
#method2
result2 = permutedims.(array[:,:,i] for i = 1:2)
``````

You don’t want to broadcast the call to `permutedims` here, you just need to call the function directly:

``````julia> x = reshape(1:12, (2, 3, 2))
2×3×2 reshape(::UnitRange{Int64}, 2, 3, 2) with eltype Int64:
[:, :, 1] =
1  3  5
2  4  6

[:, :, 2] =
7   9  11
8  10  12

julia> permutedims(x, (2, 1, 3))
3×2×2 Array{Int64, 3}:
[:, :, 1] =
1  2
3  4
5  6

[:, :, 2] =
7   8
9  10
11  12
``````
2 Likes

Thanks @rdeits , I’m sorry, I couldn’t find in the documentation where it details what ,(2,1,3) represents. Will you please point me to where I can find it? Thank you!

(2,1,3) is the permutation. It means move 2 to 1, 1 to 2, and leave 3 at 3.

2 Likes

Legendary, got it!

1 Like