简体   繁体   English

在Matlab中对3维矩阵的每一行中的元素进行排序

[英]Sort elements in each row of a 3-d matrix in Matlab

I want to sort the elements in each row of a 3-d matrix A in Matlab. 我想在Matlab中对3维矩阵A每一行中的元素进行排序。 This matrix has dimension (m)x(n)x(g) . 该矩阵的尺寸为(m)x(n)x(g) g is set equal to 3 . g设置为等于3 The order should be done in ascending order, firstly wrto A(:,:,1) , then A(:,:,2) and finally A(:,:,3) . 该顺序应按升序执行,首先是wrto A(:,:,1) ,然后是A(:,:,2) ,最后是A(:,:,3)

For example: 例如:

A(:,:,1)=[3 1 1; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 3 4; 1 4 0; 0 1 0; 2 1 7];
A(:,:,3)=[6 7 9; 6 6 0; 6 5 0; 0 0 0];

%Step 1: Order wrto A(:,:,1)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 1 0; 2 1 7];
A(:,:,3)=[7 9 6; 6 6 0; 6 5 0; 0 0 0];

%Step 2: Within the order in Step 1, order wrto A(:,:,2)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 0 1; 1 2 7];
A(:,:,3)=[7 9 6; 6 6 0; 6 0 5; 0 0 0];

%Step 3: Within the order in Step 1 and 2, order wrto A(:,:,3)
A(:,:,1)=[1 1 3; 4 5 6; 0 0 0; 1 1 1];
A(:,:,2)=[3 4 3; 1 4 0; 0 0 1; 1 2 7];
A(:,:,3)=[7 9 6; 6 6 0; 0 6 5; 0 0 0];

You can apply sortrows to each horizontal slice of A , seen from above (so that the third dimension becomes the "rows" in " sort rows "): 可以应用sortrows到的每个水平片段 A从上面看 (使得第三维成为“的“行” sort rows ”):

B = NaN(size(A));
for n = 1:size(A,1),
    B(n,:,:) = sortrows(squeeze(A(n,:,:)));
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM