Search this blog!

Tuesday, December 13, 2011

In MATLAB: Sort an Array and then Undo that sort

PROBLEM:
--------------
Imagine I have an array to be sorted and after I sort it I want to UNDO that sort so that the array came back to the initial condition.

How?
---------
 A=[10 9 7 4 5 7 5 3 ];
>> [SORTED_A,IX]=sort(A)

SORTED_A =
     3     4     5     5     7     7     9    10
IX =
     8     4     5     7     3     6     2     1

>> UNSORTED=1:length(A)
UNSORTED =
     1     2     3     4     5     6     7     8

>> NEW_INDEX(IX)=UNSORTED
NEW_INDEX =
     8     7     5     2     3     6     4     1


>> NEW_A=SORTED_A(NEW_INDEX)
NEW_A =
    10     9     7     4     5     7     5     3

>> isequal(A,NEW_A)

ans =

     1

No comments:

Post a Comment