且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Matlab中重新排列矩阵每一行中的元素

更新时间:2023-08-28 16:37:34

请参见下面的注释代码,该代码复制了代码的结果.它使用sort两次,包括排序索引输出.如果G中的值相等,则是第一次确定您描述的抢七局情况.第二次是根据G排序.

See the below commented code which reproduces your code's results. It uses sort, including the sorting indices output, twice. The first time is to decide the tie-break situation you described if values in G are equal. The second time is to sort according to G.

在我的PC上,它以8000x20大小的矩阵运行,大约需要0.017秒.

On my PC, it runs with matrices of size 8000x20 in around 0.017 secs.

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,以说明其给出的绝对矩阵元素数,请注意它们都是唯一的!

This first image shows an example matrix iX, to illustrate how the indices are just relative within each row. The second image shows iX+ofsts to illustrate the absolute matrix element number it gives, note they are all unique!

iX

iX+ofsts