Reshaping Arrays

Every abstract array in Julia has a shape that determines how that array behaves with respect to indexing and certain array operations.

The shape of an array is fully specified by a tuple of lengths called its dimensions, which tell you how long the array is in each direction.

You can see the dimensions of an array using size:

size([1 2 3; 4 5 6])(2, 3)
size(1:4)(4,)

Reshaping an array means changing its dimensions. For example, here's a simple four-element range:

1:41:4
12341234range

The range is shaped like a one-dimensional column. We can reshape it to a two-dimensional square with reshape:

reshape(1:4, (2, 2))[1 3; 2 4]
12121234reshaped array

We can reshape to a row vector the same way, keeping in mind that row vectors in Julia are represented by 1-by-n arrays:

reshape(1:4, (1, 4))[1 2 3 4]
112341234reshaped array

Reshaping an array preserves the product of its dimensions — the number of elements stays unchanged.

As a convenience you can pass : as one of the dimensions to ask reshape to compute the value of that dimension for you:

reshape(1:8, (2, :))[1 3 5 7; 2 4 6 8]
12123412345678reshaped array

Convenience Functions

In addition to reshape there are several convenience functions for reshaping arrays in particular ways.

The function vec reshapes into a one-dimensional column vector:

vec([1 3; 2 4])[1, 2, 3, 4]
12341234array

The function dropdims removes dimensions of length 1, known as singleton dimensions. For example, you can turn a 1x2 array into a vector of length 2 by dropping the first dimension:

dropdims([1 2 3 4], dims=1)[1, 2, 3, 4]
12341234array

reshape itself has a short form — you can omit the () around the dimensions and pass them individually:

reshape(1:4, 2, 2)[1 3; 2 4]
12121234reshaped array

Related Functions

You can exchange or otherwise permute the dimensions of a matrix using permutedims:

permutedims([1 2; 3 4])[1 3; 2 4]

You can rotate the contents of a matrix by 90° or 180° degrees:

rotl90([1 2; 3 4])[2 4; 1 3]
12122143array
rotr90([1 2; 3 4])[3 1; 4 2]
12123412array
rot180([1 2; 3 4])[4 3; 2 1]
12124231array

This is a draft. If you have feedback, email me.

Thanks for reading!

Yuri

now()2018-09-15T06:16:00.983