[英]Reordering the elements in each row of a matrix in Matlab
I have two matrices X
and G
in Matlab of the same dimension MxN
. 我在Matlab中有两个矩阵X
和G
,它们的维数为MxN
。 I want to order each row of both as described below 我想按如下所述对两者的每一行进行排序
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
This code does what I want 这段代码可以满足我的要求
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
However it may slow when M
is large. 但是,当M
大时,它可能会变慢。 For example, with M=8000
and N=20
it takes approx 0.6 sec, which is a lot as I have to repeat the procedure several times. 例如,在M=8000
和N=20
情况下,大约需要0.6秒,这对我不得不重复几次该过程来说是很大的。
Do you have more efficient suggestions? 您有更有效的建议吗?
Example 例
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];
See the below commented code which reproduces your code's results. 请参见下面的注释代码,它复制了代码的结果。 It uses sort
, including the sorting indices output, twice. 它两次使用sort
(包括输出排序索引)。 The first time is to decide the tie-break situation you described if values in G
are equal. 如果G
中的值相等,则是第一次确定您描述的抢七局情况。 The second time is to sort according to G
. 第二次是根据G
排序。
On my PC, it runs with matrices of size 8000x20
in around 0.017 secs. 在我的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.
Edit: 编辑:
This first image shows an example matrix iX
, to illustrate how the indices are just relative within each row. 该第一张图片显示了示例矩阵iX
,以说明索引如何在每一行内相对。 The second image shows iX+ofsts
to illustrate the absolute matrix element number it gives, note they are all unique! 第二张图片显示了iX+ofsts
以说明它给出的绝对矩阵元素数,请注意它们都是唯一的!
iX
iX+ofsts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.