Array permutations and shape changes
Many Engee functions use array elements and give them a different shape or sequence. This can be useful for pre-processing data, for later calculations, or for analysing data.
Changing the shape
The reshape function changes the size and shape of an array. For example, convert a matrix of size 3 4 to a matrix of size 2 6.
A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
B = reshape(A,2,6)
Using the elements from A you can create a multidimensional array that will contain 3 matrices of size 2 2.
C = reshape(A,2,2,3)
Transpose and flip
A common task in linear algebra is to work with matrix transpose, which turns rows into columns and columns into rows. To do this, use the function transpose or the operator '.
A = rand(3, 3)
A'
B = [1+im 1-im; -im im]
transpose(B)
The function reverse moves rows up and down and columns from left to right depending on the value of the keyword dims.
dims = 1 # Work with rows
dims = 2 # Work with columns
A = [1 2; 3 4]
B = reverse(A, dims=1)
С = reverse(A, dims=2)
Offset and rotation
You can shift the elements of an array by a certain number of positions using the function circshift. For example, create a matrix of size 3 4 and shift its columns to the right by 2. The second argument [0 2] tells circshift to shift the rows 0 places and the columns 2 places to the right.
A = [1 2 3 4; 5 6 7 8; 9 10 11 12]
B = circshift(A,[0 2])
To move the rows from A up 1 and keep the columns in place, specify the second argument as [-1 0].
C = circshift(A,[-1 0])
A = [1 2; 3 4]
Sorting
Sorting data in an array is also a valuable tool. For example, the function sort sorts the elements of each row or column of a matrix separately in ascending or descending order. The value of the dims keyword tells you which rows or columns are being sorted.
Create a matrix A and sort each column from A in ascending order.
A = rand(4,4)
B = sort(A, dims=1)
If you specify the value of the keyword rev = true, the sorting will not be in ascending order, but in descending order.
C = sort(A, dims=2, rev=true)
Conclusion
In this article we have considered some functions for matrix transformation: reshaping, traspanning, shifting and rotating, as well as sorting. More information on matrix operations can be found in Linear Algebra.