我在相同维度X
的Matlab中有两个矩阵G
和MxN
。我想按如下所述订购两者的每一行
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=8000
和N=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 :(得分:1)
请参阅下面注释的代码,该代码可以重现您的代码的结果。它使用arm-none-eabi-gdb
,包括排序索引输出两次。如果sort
中的值相等,则第一次决定您描述的抢七局面。第二次是根据G
进行排序。
在我的电脑上,它使用大小为G
的矩阵运行大约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