2
votes

I have a 3D matrix. Say it is:A = randi(15,[4,3,2]). I want to sort the 2nd column of each layer in an ascending order, but the other columns simply stayed in their respective rows. How can I do that? If the two layers are like this

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

Then I want a result like this

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
Welcome to StackOverflow! Please consider accepting the answer, if it helped you. Thank you!Robert Seifert

1 Answers

1
votes

If you have the Image Processing Toolbox, using blockproc is one solution:

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, []) 

Without the toolbox, maybe a little slower:

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