0

Hi i have a 289x2 array that i want to sort in MatLab. I want to sort the first column into numerical ascending order. However I want to keep the second column entry that is associated with it. Best way to explain is through an example.

x = 76  1 
    36  2 
    45  3 

Now I want to sort x so that it returns an array that looks like:

x = 36  2
    45  3
    76  1

So the first column has been sorted into numerical order but has retained its second column value. So far I have tried sort(x,1). This sorts the first column as i want but does not keep the pairing. This returns x as:

x = 36  1
    45  2
    76  3

Any help would be great. Cheers!!

1 Answer 1

3

This is exactly what sortrows does.

x=sortrows(x);    % or x=sortrows(x,1);

or if you want to use sort then get the sorted indexes first and then arrange the rows accordingly like this:

[~, idx] = sort(x); %Finding the sorted indexes
x = x(idx(:,1),:) ; %Arranging according to the indexes of the first column

Output for both approaches:

x =
   36     2
   45     3
   76     1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.