%% Reshaping and Rearranging Arrays
% Many functions in MATLAB® can take the elements of an existing array and put them in a different shape or sequence. This can be helpful for preprocessing your data for subsequent computations or analyzing the data.
%% Reshaping
% The reshape function changes the size and shape of an array. For example, reshape a 3-by-4 matrix to a 2-by-6 matrix.

A = [1 4 7 10; 2 5 8 11; 3 6 9 12]
B = reshape(A,2,6)

% As long as the number of elements in each shape are the same, you can reshape them into an array with any number of dimensions. Using the elements from A, create a 2-by-2-by-3 multidimensional array.

C = reshape(A,2,2,3)

%% Transposing and Flipping
% A common task in linear algebra is to work with the transpose of a matrix, which turns the rows into columns and the columns into rows. To do this, use the transpose function or the .' operator.
% Create a 3-by-3 matrix and compute its transpose.

A = magic(3)
B = A.'

% A similar operator ' computes the conjugate transpose for complex matrices. This operation computes the complex conjugate of each element and transposes it. Create a 2-by-2 complex matrix and compute its conjugate transpose.

A = [1+i 1-i; -i i]
B = A'

% flipud flips the rows of a matrix in an up-to-down direction, and fliplr flips the columns in a left-to-right direction.

A = [1 2; 3 4]
B = flipud(A)
C = fliplr(A)

%% Shifting and Rotating
% You can shift elements of an array by a certain number of positions using the circshift function. For example, create a 3-by-4 matrix and shift its columns to the right by 2. The second argument [0 2] tells circshift to shift the rows 0 places and shift 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 shift the rows of A up by 1 and keep the columns in place, specify the second argument as [-1 0].

C = circshift(A,[-1 0])

% The rot90 function can rotate a matrix counterclockwise by 90 degrees.

A = [1 2; 3 4]
B = rot90(A)

% If you rotate 3 more times by using the second argument to specify the number of rotations, you end up with the original matrix A.

C = rot90(B,3)

%% Sorting
% Sorting the data in an array is also a valuable tool, and MATLAB offers a number of approaches. For example, the sort function sorts the elements of each row or column of a matrix separately in ascending or descending order. Create a matrix A and sort each column of A in ascending order.

A = magic(4)
B = sort(A)

% Sort each row in descending order. The second argument value 2 specifies that you want to sort row-wise.

C = sort(A,2,'descend')

% To sort entire rows or columns relative to each other, use the sortrows function. For example, sort the rows of A in ascending order according to the elements in the first column. The positions of the rows change, but the order of the elements in each row are preserved.

D = sortrows(A) 

% Copyright 2018 The MathWorks, Inc.