sort a one dimensional array ascend and descend
Show older comments
To sort a vector in ascending order it would seem completely obvious to type
sort([1,3,2],1,'ascend')
Who cares what the second argument is, when the first is a vector?
But matlab views [1,3,2] as a 1x3 vector, so that you have to set the second arguemnt to 2.
Since matlab can recognize a vector with
isvector
Is there any reason why the sort command doesn't simply ignore the second argument when the first is a vector? This would save many people hours of puzzlement I think.
1 Comment
"Who cares what the second argument is, when the first is a vector?"
I do (and probably many other users too).
When I specify that I want the columns sorted, then I want the columns sorted. It does not matter one iota that the columns might have only one row, or no rows, or one million rows. Lets assume that my algorithm requires me to sort based on columns... then your proposal would mean that suddenly, in the middle of millions of loops when my data first has just one row, that MATLAB should decide that it knows better than me and will sort along the row, even though I specified the columns.
MATLAB is a tool which relies on users having some ability in keeping track of what shape and form their data is in, and hopefully also being able to read the documentation. Should MATLAB be re-designed at the level of users who cannot do this? With a line or two of code you can do all kinds of destructive, or meaningless operations: does MATLAB (or any other language) stop users from writing them? Would you really want to use a language that did not do what you told it to do?
"Is there any reason why the sort command doesn't simply ignore the second argument when the first is a vector?"
Because this would make perfectly good algorithms break, create so many bugs, and require awful, ugly workarounds. Because this would make MATLAB unusable.
Accepted Answer
More Answers (2)
It is consistent behaviour: You explicitly ask to sort a 1xn vector along the first dimension. I think it would be nice if Matlab issues a warning that points out that you have written a command that sorts nothing at all, or that you do not need the second numeric argument if the first is a vector.
Mischa Kim
on 6 Sep 2016
Hi Leo, you can always use
sort([1,3,2],'ascend')
and even
sort([1,3,2])
As for your question: there might be scenarios where the size of the array is not known and you only want to sort along the first dimension, the rows in a 2-dim array. There might be others. But essentially, you do not want to define "standard" behavior that can have limiting or even unwanted side effects.
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!