2017-03-23 74 views
0

同じ次元のMatlabに2つの行列XGがあります。MxNです。私は、このコードは、私がMが大きい場合、それは遅くてもよいがMatlabの行列の各行の要素の並び替え

A(:,:,1)=X; 
A(:,:,2)=G;  
B=zeros (size(A,1),2*N); 
for i = 1:size(A,1), 
    B(i,:) = reshape(sortrows(squeeze(A(i,:,:)), [-2 -1]),1,2*N); 
end 

を望むもの行い

clear all 
rng default; 
M=12; 
N=3; 
X=randi([0 1], M,N); 
G=randi([0 1], M,N); 


%for i=1,...N 
% List in descending order the elements of G(i,:) 
% If G(i,h)=G(i,j), then order first G(i,h) if X(i,h)>X(i,j), and 
% order first G(i,j) if X(i,j)>X(i,h). If G(i,h)=G(i,j) and  
% X(i,j)=X(i,h), then any order is fine. 
% Use the order determined for G(i,:) to order X(i,:). 
% Combine the ordered X(i,:) and G(i,:) in B(i,:) 
%end 

以下に説明するように、両方の各行を注文したいです。たとえば、M=8000N=20の場合、約0.6秒かかるため、手順を何度も繰り返す必要があります。

あなたはより効率的な提案をしていますか?

X=[0 0 0 1; 
    1 1 0 0]; 

G=[0 1 0 1; 
    0 0 1 0]; 

B=[1 0 0 0 | 1 1 0 0; 
    0 1 1 0 | 1 0 0 0]; 
+0

あなたは、入力と出力の小さな例を投稿する場合、それはあなたが、私が追加した –

+0

と例望むものそれを明確にするために、役立ちます – user3285148

答えて

1


例は、コードの結果を再現する以下のコメントコードを参照してください。これは、並べ替え指数出力を含む、sortを2回使用します。最初に、Gの値が等しい場合に記述したタイブレークの状況を判断します。 2回目はGに従ってソートすることです。

私のパソコンでは、サイズが8000x20の行列を約0.017秒で実行します。

clear 
rng default; 
% Set up random matrices 
M=8000; 
N=20; 
X=randi([0 1], M,N); 
G=randi([0 1], M,N); 
tic; 

% Method: sort X first to pre-decide tie-breakers. Then sort G. Then merge. 

% Sort rows of X in descending order, store sorting indices in iX 
[X,iX] = sort(X,2,'descend'); 
% The indices iX will be relative to each row. We need these indices to be 
% offset by the number of elements in a column, so that the indices refer 
% to each specific cell in the matrix. (See below for example). 
ofsts = 1 + repmat((0:M-1)', 1, N); 
% Reorder G to be sorted the same as X was. 
G = G((iX-1)*M + ofsts); 
% Sort rows of G in descending order and store the sorting indices iG. 
[G,iG] = sort(G,2,'descend'); 
% Reorder X to be sorted the same as G. 
X = X((iG-1)*M + ofsts); 
% Merge the two matrices 
B = [X, G]; 

toc; 
% Elapsed time < .02 secs for 8000x20 matrices. 

編集:

この最初の画像は、インデックスがちょうど各列内の相対的なものである方法を説明するために、例えばマトリックスiXを示します。 2番目の画像はiX+ofstsを示しています。それは絶対行列要素番号を示しています。

iX

iX

iX+ofsts

iX + ofsts

+0

あなたは同様の質問を見ることができますか?https://stackoverflow.com/questions/45286752/reordering-discrete-elements-in-each-行の - の - マトリックスのmatlabに? – user3285148

関連する問題