Take the 2-minute tour ×
Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Is there a function in MATLAB that sorts a bidimensional array?

This is how I would like to sort it:

The matrix:

$\left(\begin{array}{c c c} 9 & 4 & 7\\ 1 & 5 & 2\\ 3 & 6 & 8 \end{array}\right) $

will become:

$\left(\begin{array}{c c c} 1 & 2 & 3\\ 4 & 5 & 6\\ 7 & 8 & 9 \end{array}\right) $

share|improve this question
add comment

1 Answer

up vote 3 down vote accepted

It should be possible by vectorizing of the original matrix and subsequent reshaping

>> A = [9 4 7; 1 5 2; 3 6 8 ]

>> reshape(sort(A(:)),size(A))'

If you need to know original indices, function sort is able to return them. But it returns indices of vectorized matrix and therefore ind2sub has to be used

A = [9 4 7; 1 5 2; 3 6 8 ];
[t,indices]=sort(A(:));
[I,J] = ind2sub(size(A),indices);
row_orig = reshape(I,size(A))';
col_orig = reshape(J,size(A))';
sorted = reshape(t,size(A))';
share|improve this answer
    
Thanks. Anyway, I think I will have to implement some algorithm manually because I need to know in another matrix or something, the original position of each sorted element :/ Is there a function or some trick that allows me to do this? –  Oscar Mederos Apr 11 '11 at 0:53
    
tHANK YOU VERY MUCH...I need to know the original position of each sorted element :/ Is there a function or some trick that allows me to do this –  user14474 Aug 11 '11 at 9:31
    
@nagaraj: I have converted your answer to a comment. Because you do not have 50 reputation points yet, you can only comment on your own questions and answers. So, you didn't do anything wrong; the "add comment" button will only appear for you once you gain 50 points. Here is an explanation of reputation points. –  Zev Chonoles Aug 11 '11 at 13:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.