The transpose of a matrix converts a matrix A in to a matrix A' such that A(i, j) = A'(j, i). This is a common manipulation of matrices which has uses throughout linear algebra. The following functions perform similar changes to matrices.
Given an m × n matrix A, and a second pair of integers m1 × n1 such that m*n = m1*n1, then the B = reshape(A, [m1, n1]) function creates a new m1 × n1 matrix where the rows of B are filled follwing the rows of A:
>> A = [1 2 3 4 5 6; 7 8 9 10 11 12] % arrows added for emphasis A = 1 | 2 | 3 4 5 6 7 v 8 v 9 10 11 12 >> reshape( A, [3, 4] ) % arrows added for emphasis ans = 1 | 8 | 4 11 7 | 3 v 10 6 2 v 9 5 12
In order to create a matrix which is filled according to the columns, use the transpose operator:
>> A = [1 2 3 4 5 6; 7 8 9 10 11 12] % arrows added for emphasis A = --------> 1 2 3 4 5 6 7 8 9 10 11 12 >> reshape( A', [3, 4] )' ans = ----> 1 2 3 4 5 6 7 8 9 10 11 12
This routine rotates the matrix by 90 degrees. If A is an m × n matrix and B = rot90(A), then A(i, j) = B(n - j + 1, i).
>> A = [1 2 3; 4 5 6] ans = 1 2 3 4 5 6 >> rot90( A ) ans = 3 6 2 5 1 4
This routine flips the rows of the matrix. If A is an m × n matrix and B = flipud(A), then A(i, j) = B(m - i + 1, j).
>> A = [1 2 3; 4 5 6] ans = 1 2 3 4 5 6 >> flipud( A ) ans = 4 5 6 1 2 3
This routine flips the columns of the matrix. If A is an m × n matrix and B = fliplr(A), then A(i, j) = B(i, n - j + 1).
>> A = [1 2 3; 4 5 6] ans = 1 2 3 4 5 6 >> fliplr( A ) ans = 3 2 1 6 5 4
This is a general flipping routine where the second argument indicates which dimension should be flipped. For a matrix A, flipdim( A, 1 ) = flipud( A ) and flipdim( A, 2 ) = fliplr( A ).
This routine extracts the upper triangular portion of a matrix. That is, given a matrix A and B = triu(A), then B(i, j) == 0 whenever i > j.
>> A = [1 2 3; 4 5 6; 7 8 9; 10 11 12] ans = 1 2 3 4 5 6 7 8 9 10 11 12 >> triu( A ) ans = 1 2 3 0 5 6 0 0 9 0 0 0
If called with a 2nd integer argument, like diag, the zeros are shifted either to the left (negative) or right (positive). triu(A) is equivalent to triu(A, 0).
>> triu( A, 2 ) ans = 0 0 3 0 0 0 0 0 0 0 0 0
This routine extracts the lower triangular portion of a matrix. That is, given a matrix A and B = tril(A), then B(i, j) == 0 whenever i < j.
>> A = [1 2 3; 4 5 6; 7 8 9; 10 11 12] ans = 1 2 3 4 5 6 7 8 9 10 11 12 >> tril( A ) ans = 1 0 0 4 5 0 7 8 9 10 11 12
If called with a 2nd integer argument, like diag, the zeros are shifted either to the left (negative) or right (positive). tril(A) is equivalent to tril(A, 0).
>> tril( A, -2 ) ans = 0 0 0 0 0 0 7 0 0 10 11 0