Reputation: 115
Easiest way is to show you through excel:
Unsorted:
Sorted:
This example is with excel, but I would need to do the same thing in matlab with thousands of entries (with 2 rows if possible).
Here is my code so far:
%At are random numbers between 0 and 2, 6000 entries.
[sorted]=sort(At);
max=sorted(end);
min=sorted(1);
%need the position of the min and max
But this is only 1 row that's being sorted and it has no numbers in the second row, and no index. How would I add one and keep it following my first row?
Thank you!
Upvotes: 0
Views: 173
Reputation: 16126
I don't have access to Matlab, but try
[sorted, I] = sort(At);
Where I will be a corresponding vector of indices of At. See the Matlab Documentation for details.
Upvotes: 2
Reputation: 114538
You have a couple of options here. For the simple case where you just need the indices, the fourth form of sort
listed in the docs already does this for you:
[sorted, indices] = sort(At);
In this case, At(indices)
is the same as sorted
.
If your "indices" are actually another distinct array, you can use sortrows
:
toSort = [At(:) some_other_array(:)];
sorted = sortrows(toSort);
In this case sorted(:, 1)
will be the sorted
array from the first example and sorted(:, 2)
will be the other array sorted according to At
.
sortrows
accepts a second parameter which tells you the column to sort by. This can be a single column or a list of columns, like in Excel. It can also provide a second output argument, the indices, just like regular sort
.
Upvotes: 1