0
votes

I am having trouble sorting a 3D matrix by whichever row I want, but still having the other two columns match up with the one sorted row.

ex)before sort:

    5 4 1 
    4 6 3
    9 6 5

after sort:

    1 4 5
    3 6 4
    5 6 9

So only the first row got sorted in ascending order, the other two rows simply stayed in their respective columns.

I have tried sort(Matrix(1,:,:)), but this seems to sort all three rows.I'm guessing there is some matlab function that can do this, but I haven't found anything. Thanks

2
Just to clarify, what you have here is a 2D matrix.Benoit_11
My mistake, I am dealing with a color image with dimention 100x100x3. 3 representing red green and blue. Same issue thoughDark
Ok then my answer below should help you. I'll edit it.Benoit_11
awesome thanks a lotDark
Great you're welcome!Benoit_11

2 Answers

2
votes

You can use output arguments with sort to reorder the matrix as you want with indexing.

Example:

clear
clc

a = [5     4     1
     4     6     3
     9     6     5]

 %// Select row of interest
 row = 1;

 [values,indices] = sort(a(row,:)) %// Since you have a 3D matrix use "a(row,:,:)"

 b = a(:,indices) %// In 3D use "b = a(:,indices,:)"

Output:

b =

     1     4     5
     3     6     4
     5     6     9
1
votes

Another approach using sortrows

%// Input
a = [5     4     1
     4     6     3
     9     6     5]

%// code
sortrows(A.').'           %// for 2D

%// Results:
 1     4     5
 3     6     4
 5     6     9
------------------------------------------------
[t,ind] = sortrows(A(:,:,1).')    %// for 3D
A(:,ind,:)