How do I sort the rows in one array based on the row order of another array?

1 回表示 (過去 30 日間)
Brad
Brad 2015 年 11 月 9 日
コメント済み: Brad 2015 年 11 月 10 日
I have 2 matrices;
C is 7 x 3 double and G is a 9 x 3 double;
C = [1 1 0; 1 0 1; 0 1 1; 1 0 0; 0 1 0; 0 0 1; 0 0 0];
G = [0 1 1; 0 0 0; 1 0 0; 1 0 1; 0 0 1; 0 0 0; 0 1 1; 1 0 0; 1 0 0];
I’m attempting to create a subset of C (New_C), based on the contents of G, where the order of the rows appearing in New_C are identical to those in C. The proper output would be as follows;
New_C = [ 1 0 1; 0 1 1; 1 0 0; 0 0 1; 0 0 0];
I am able to attain the unique rows in G with the following;
New_C = unique(G, ‘rows’);
But the rows are not in their proper order.
Is there a way to re-order/sort the rows in New_C such that their order matches the rows in C ?
Thanks you.

採用された回答

James Tursa
James Tursa 2015 年 11 月 9 日
Try this (Caution, untested since I am not on a machine with MATLAB at the moment):
[~,Locb] = ismember(New_C,C,'rows');
New_C = C(sort(Locb),:);
Assumes all rows of New_C can be found in C.
  1 件のコメント
Brad
Brad 2015 年 11 月 10 日
James, thanks for the push!
I had to make a mod and add some code, but it works:
% Find the subset of C
[~,Locb] = ismember(G,C,'rows');
New_C = C(sort(Locb),:);
% Get the unique values and sort
[~,idx]=unique(New_C,'rows');
out=New_C(sort(idx),:);

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

その他の回答 (0 件)

カテゴリ

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