每个3D矩阵的每一层排序一列

时间:2015-12-06 15:41:35

标签: matlab sorting matrix

我有一个3D矩阵。说它是:A = randi(15,[4,3,2])。我想按升序对每一层的第二列进行排序,但其他列只是停留在各自的行中。我怎样才能做到这一点? 如果这两层是这样的

val(:,:,1) =

 6    12    13
10    14     8
15     8     2
 4     3    14


val(:,:,2) =

10     1     8
 2    15    12
14    11     1
 1     6    11

然后我想要一个像这样的结果

val(:,:,1) =
 4     3    14
15     8     2
 6    12    13
10    14     8

val(:,:,2) =
10     1     8
 1     6    11
14    11     1
 2    15    12

1 个答案:

答案 0 :(得分:1)

如果您有图像处理工具箱,使用blockproc是一种解决方案:

val(:,:,1) = [ ...
 6    12    13
10    14     8
15     8     2
 4     3    14]


val(:,:,2) = [ ...
10     1     8
 2    15    12
14    11     1
 1     6    11] 


%// row indices to used for sorting
rowidx = 2;


[n,m,p] = size( val );

%// get a 2D matrix
val2D = reshape(val, n, [], 1) 

%// sorting
out2D = blockproc(val2D,[n,m],@(x) sortrows(x.data,rowidx))

%// transform back to 3D
out3D = reshape(out2D, n, m, []) 

没有工具箱,可能会慢一点:

temp = arrayfun(@(x) sortrows(val(:,:,x),rowidx),1:size(val,3),'uni',0)
out3D = cat(3,temp{:})
out3D(:,:,1) =

     4     3    14
    15     8     2
     6    12    13
    10    14     8


out3D(:,:,2) =

    10     1     8
     1     6    11
    14    11     1
     2    15    12