Octave: Unrolling and reshaping

Most optimization functions in Octave such as fminunc expect vectors the parameter to be optimized. However, sometimes (e.g. in the field of neural networks) the vector representation is somewhat unnatural and clumsy to work with. Converting between vector and matrix representation is referred to as unrolling (matrix -> vector) and reshaping (vector -> matrix).

Unrolling

Unrolling is quite simple. Given a matrix A, you have two different possibilities of addressing the elements of A. Either you address rows and colums separately, i.e., A(i,j) or you use one single index or index range A(k) which indexes A column by column (Remember that the colon stands for the range from 1 to end):

As you can see, A(:) is exactly what we want: A vector representation of the matrix.

Reshaping

The reverse way, reshaping, is performed by a command called reshape. It takes as arguments the vector to be reshaped and the row and column count of the target matrix. Continuing the example from above, we get the following:

Unrolling and reshaping with multiple matrices

Say you have multiple matrices,  A,B, and C. Then the described procedure works analogously:

Leave a Reply

Your email address will not be published. Required fields are marked *

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box