Integrating Indices

Hello,
I have taken the matrix below and sorted it ascending by row:
(Original) A=[1 4 5; 3 -1 8; 12 7 9; 4 10 -5];
(Sorted By Row) B=[1 4 5; -1 3 8; 7 9 12; -5 4 10];
I would like to have the indices of the original matrix appear in the locations of the sorted matrix. For this case it would look like this.
(Original) A=[1 2 3; 1 2 3; 1 2 3; 1 2 3];
(Sorted By Row) B=[1 2 3; 2 1 3; 2 3 1; 3 1 2];
I have tried several different methods but with no luck. Any assistance is appreciated
Thanks

1 Comment

zohar
zohar on 21 Feb 2011
Hi Daniel
Give us some code and use the code formatting.

Sign in to comment.

 Accepted Answer

[sorted_A, sort_indexes] = sort(A,2);

2 Comments

Daniel
Daniel on 21 Feb 2011
Thank you, it still isn't quite what I need.I may have worded the question wrong.
Oleg Komarov
Oleg Komarov on 21 Feb 2011
All of your examples are solved with Walter's solution!

Sign in to comment.

More Answers (2)

Daniel
Daniel on 21 Feb 2011
A=[ 4 3; 8 4;-1 -5; 2 7];
A1=A
[m,n]=size(A);
for o=1:n
A1=A;
min_val=A(1);
for i=1:n-1
for j=1:m
if A(j,i)>A(j,i+1);
A(j,i+1)=A(j,i);
A(j,i)=A1(j,i+1);
end
end
end
end
A
comp=isreal(A)
if comp==0
A2=abs(A);
else
A2=A;
end
This is what I currently have. The first for loops sort the matrix by row. The second section ensures a real answer.

1 Comment

Oleg Komarov
Oleg Komarov on 21 Feb 2011
Have you tried Walter's solution?

Sign in to comment.

Daniel
Daniel on 21 Feb 2011
Yes I have tried Walter's solution. When added to my code it yeilds the following.
sort_indexes =
1 2
1 2
1 2
1 2
For these two matrices, it should read:
sort_indexes =
2 1
2 1
2 1
1 2
this is much closer to what I need, but if it worked properly it would display the indexes of the first matrix in the positions in the second matrix. Is there any way to obtain this solution?

2 Comments

Oleg Komarov
Oleg Komarov on 21 Feb 2011
A=[ 4 3; 8 4;-1 -5; 2 7];
[sorted_A, sort_indexes] = sort(A,2)
gives exactly the second matrix...
Daniel
Daniel on 21 Feb 2011
I apologize, something was wrong with the way that I had input this solution. Both you and Walter are Correct.
Thank you

Sign in to comment.

Categories

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!