Efficient Multi Column Sorting of Matrices

13 ビュー (過去 30 日間)
Alexander
Alexander 2012 年 11 月 16 日
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

採用された回答

Matt J
Matt J 2012 年 11 月 16 日
A2 = sortrows(A,[2,1]);
  1 件のコメント
Alexander
Alexander 2012 年 11 月 16 日
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

サインインしてコメントする。

その他の回答 (1 件)

カテゴリ

Help Center および File ExchangeShifting and Sorting Matrices についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by