MATLAB: Sorting the elements of a matrix, Part 3

MATLABmatrix

Suppose I have a matrix A. I want to define a matrix B where, for each row, taking entries in the first column and the second column, sort entries so that the entry in the first col will be higher than the one in the second column, and for the entries in the third and the fourth column, conduct the same operation.
For example, for
A=[1 2 3 4; 5 6 7 8]
we should have
B=[2 1 4 3; 6 5 8 7]
But I need to make it work for an arbitrary (even columns) matrix.

Best Answer

If you want the sorting on 2x2 sub-matrices, create 2x2 sub-matrices at first:
AA = reshape(A, 2, 2, 2);
BB = sort(AA, 2, 'descend');
B = reshape(BB, 2, 4)