Sorting the elements of a matrix, Part 3

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.

2 Kommentare

Star Strider
Star Strider am 15 Apr. 2018
Note: The original Question was a (2x2) matrix. The (2x4) matrix is new.
alpedhuez
alpedhuez am 15 Apr. 2018
Bearbeitet: alpedhuez am 15 Apr. 2018
I meant an arbitrary size of a matrix.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

Jan
Jan am 15 Apr. 2018
Bearbeitet: Jan am 15 Apr. 2018

0 Stimmen

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)

3 Kommentare

alpedhuez
alpedhuez am 16 Apr. 2018
why 2*2?
Jan
Jan am 16 Apr. 2018
Because it give the result you have mentioned. You want to sort the first 2 columns rowwise, and the second two columns rowwise. Therefore reshape creates block matrices with the wanted size at first.
alpedhuez
alpedhuez am 16 Apr. 2018
Thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Geoff Hayes
Geoff Hayes am 15 Apr. 2018

0 Stimmen

alpedhuez - if you want to sort the rows in descending order, then try
B = sort(A,2,'descend')
See sort for details.

1 Kommentar

alpedhuez
alpedhuez am 15 Apr. 2018
Bearbeitet: alpedhuez am 21 Apr. 2018
No. There are multiple columns.
A=[1 2 3 4;5 6 7 8]
Then
B=[2 1 4 3;6 5 8 7];

Melden Sie sich an, um zu kommentieren.

Kategorien

Produkte

Tags

Gefragt:

am 15 Apr. 2018

Bearbeitet:

am 21 Apr. 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by