Efficient Multi Column Sorting of Matrices

14 vues (au cours des 30 derniers jours)
Alexander
Alexander le 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

Réponse acceptée

Matt J
Matt J le 16 Nov 2012
A2 = sortrows(A,[2,1]);
  1 commentaire
Alexander
Alexander le 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

Connectez-vous pour commenter.

Plus de réponses (1)

Catégories

En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by