%% Shifting and Sorting Matrices
% You can sort matrices, multidimensional arrays, and cell arrays of character vectors along any dimension and in ascending or descending order of the elements. The sort functions also return an optional array of indices showing the order in which elements were rearranged during the sorting operation.
%% Shifting Location of Matrix Elements
% The circshift function shifts the elements of a matrix in a circular manner along one or more dimensions. Rows or columns that are shifted out of the matrix circulate back into the opposite end. For example, shifting a 4-by-7 matrix one place to the left moves the elements in columns 2 through 7 to columns 1 through 6, and moves column 1 to column 7.
% Create a 5-by-8 matrix named A and shift it to the right along the second (horizontal) dimension by three places (you would use [0,-3] to shift to the left by three places):

A = [1:8; 11:18; 21:28; 31:38; 41:48]
B = circshift(A, [0, 3])

% Now take A and shift it along both dimensions: three columns to the right and two rows up:

A = [1:8; 11:18; 21:28; 31:38; 41:48];
B = circshift(A, [-2, 3])

% Since circshift circulates shifted rows and columns around to the other end of a matrix, shifting by the exact size of A returns all rows and columns to their original location:

B = circshift(A, size(A));
all(B(:) == A(:))  % Check that all elements of B equal A

%
%% Sorting Matrix Data
% The sort function sorts matrix elements along a specified dimension. For example, create a matrix A and sort each column in ascending order. Specifying 1 as the second argument indicates columnwise sorting.

rng default;
A = floor(rand([6 7])*100)
c = sort(A, 1)
issorted(c(:, 1))

% Now sort the rows of A in descending order.

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

% When you specify a second output, sort returns the indices of the original matrix A positioned in the order they appear in the output matrix.

[r,ind] = sort(A, 2, 'descend');
ind

% The second row of index contains the sequence, 4 6 3 7 1 5 2, which means that the second row of matrix r is comprised of A(2,4), A(2,6), A(2,3), A(2,7), A(2,1), A(2,5), and A(2,2).
% The sortrows function sorts the entire row of a matrix according to the elements in a specified column, maintaining the order of elements in each row. For example, sort the rows of A in ascending order according to the values in the first column.

r = sortrows(A,1)

% Now sort the rows of A in ascending order according to the values in the fourth column:

r = sortrows(A,4)

% Copyright 2018 The MathWorks, Inc.