2017-03-23 54 views
0

我有兩個矩陣XG在Matlab中具有相同維數MxN。我想下面在Matlab中對矩陣的每一行中的元素進行重新排序

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 

描述這段代碼做什麼,我想

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 

然而,當M大可能放緩至同時訂購的每一行。例如,與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,包括排序索引輸出兩次。如果G中的值相等,則首次確定您描述的搶七局勢。第二次是根據G進行分類。

在我的PC上,它在大約0.017秒內以大小8000x20的矩陣運行。

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,來說明如何指數是每行內剛剛相對。第二張圖片顯示iX+ofsts來說明它給出的絕對矩陣元素數量,注意它們都是獨一無二的!

iX

iX

iX+ofsts

iX + ofsts

+0

你可以看看類似的問題https://stackoverflow.com/questions/45286752/reordering-discrete-elements-in-each-行列式的矩陣在matlab中? – user3285148

相關問題