MATLAB Answers

0

sorting according to another vector

Asked by Danielle Leblanc on 5 Aug 2011
Latest activity Commented on by Steven Lord
on 26 Oct 2018
Hi,
I have a vector A that doesn't follow any order. I want to sort Matrix B that has the first column of values similar to those of A but in different order. Is it possible to sort B according to A using a single function or should I write many codes to do so?

  0 Comments

Sign in to comment.

Tags

4 Answers

Answer by Walter Roberson
on 5 Aug 2011
 Accepted Answer

Sorry you will have to use multiple calls:
[a_sorted, a_order] = sort(A);
newB = B(a_order,:);

  1 Comment

Jan
on 5 Aug 2011
@Danielle: Ok, then I have misunderstood your question. The information that B has "value similar to those of A" is meaningless then - correct?

Sign in to comment.


Jan
Answer by Jan
on 5 Aug 2011

I'm not sure, if I understand the question correctly. Do you want to bring B in the same order as the unsorted A? Then either sort both vectors and mix their sorting indicies:
[As, Ai] = sort(A);
[Bs, Bi] = sort(B(:, 1));
ABi(Ai) = Bi;
Now ABi is the sorting index to bring B to the order of A:
isequal(A, B(ABi, 1)) % ==> 1
Or let ISMEMBER do this for you:
[dummy, order] = ismember(A, B(:, 1));
isequal(A, B(order, 1)) % ==> 1

  0 Comments

Sign in to comment.


Answer by Pramit Biswas on 31 Jan 2018
Edited by Pramit Biswas on 31 Jan 2018

function B = sortBlikeA(A,B)
[~, Ao] = sort(A);
Bs=sort(B);
B(Ao)=Bs;
end

  0 Comments

Sign in to comment.


Answer by inzamam shoukat on 26 Oct 2018
Edited by inzamam shoukat on 26 Oct 2018

Hi every one......i have matrix lets suppose [3 2;1 9]
what i want to do is sort out the only first column in ascending order but problem is how to do it so that corresponding values which is in first row 2 for 3 in second row 9 for 1 change their positions according to the position of values of first column being sorted i.e [1 9; 3 2]...
LIMITATION : sorting operation never applied to second column....

  2 Comments

Please ask a separate question
Use sortrows.

Sign in to comment.