【问题标题】:Reordering the elements in each row of a matrix in Matlab在Matlab中对矩阵的每一行中的元素进行重新排序
【发布时间】:2017-03-23 13:56:51
【问题描述】:

我在 Matlab 中有两个矩阵 XG 相同维度 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=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];

【问题讨论】:

  • 如果您发布一个带有输入和输出的小示例会有所帮助,以明确您想要什么
  • 我已经添加和示例

标签: matlab


【解决方案1】:

请参阅下面的注释代码,该代码重现了您的代码结果。它使用了两次sort,包括排序索引输出。第一次是在G 中的值相等时确定您描述的抢七局情况。第二次是按照G排序。

在我的 PC 上,它运行大小为 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,以说明索引如何在每一行中只是相对的。第二张图片显示iX+ofsts 来说明它给出的绝对矩阵元素编号,注意它们都是唯一的!

iX

iX+ofsts

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
相关资源
最近更新 更多