MATLAB Answers

Efficient Multi Column Sorting of Matrices

16 views (last 30 days)
Alexander
Alexander on 16 Nov 2012
Hello, my first question!
I have a set of matrices that are added to as the algorithm proceeds, in order to to reduce the processing I need to sort the arrays and remove redundant rows. Now I have almost worked out how to do it using many of the ideas on these web pages, see below. The problem is that the code is growing and it just feels like there must be a simpler approach.
As an example, assume A is the matrix, then I need to first sort A and then identify column 2 elements where there are matches, for example 2 and 3, I then need to swap the rows based on the value of column 1, as shown in A2.
A = [ 6,2; 2,3; 7,10; 2,2; 5,3; 8,9; ]
A2 is the desired outcome.
A2 = [ 2,2; 6,2; 2,3; 5,3; 8,9; 7,10;]
I begin with sorting by column 2
As = sortrows(A,2)
and then using the code below to find the matches in the column 2 field
[n, bin] = histc(As(:,1), unique(As(:,1)));
multiple = find(n > 1);
index = find(ismember(bin, multiple));
Now here is the problem, the next step will be to sort on those rows where the column 2 field are identical and to then sort on column 1. Is anyone able to help with a more efficient approach.
Many thanks

Accepted Answer

Matt J
Matt J on 16 Nov 2012
A2 = sortrows(A,[2,1]);
  1 Comment
Alexander
Alexander on 16 Nov 2012
Thanks very much. I had a feeling there was an easier way, but surely did not think it would reduce to a single line. I have tested it quite thoroughly and it is spot on.
Many thanks

Sign in to comment.

More Answers (1)

Tags

Products

Community Treasure Hunt

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

Start Hunting!

Translated by