Why is a statement like "sortrows(A)(2:4)" "invalid array indexing" and how can I circumvent adding an extra line of code to make it work?

I could write:
sorted = sortrows(A)
sorted(2:4)
However this seems clumsy and unnecessarily long to me. How can I compress it down to one statement?

 Réponse acceptée

"Why" ?
Because the original MATLAB parser was written by hand and very fragile, and was not able to handle parsing this kind of logic.
As one statement:
subsref(sortrows(A), struct('type', '()', 'subs', {2:4}))
I would suggest to you that it is much cleaner to add an auxillary function that only has to be defined once (if defined as a true function) or once per function (if defined as an anonymous function)
Index = @(array, varargin) array(varargin{:})
Index(sortrows(A), 2:4)
Are you sure that you want linear index 2 to 4 from the output of sorting rows ?? It would make more sense to take rows 2 to 4 as output
Index(sortrows(A), 2:4, ':')
Notice you must use ':' here not plain : without quotes .

3 commentaires

Thanks. In my case it's a vertical vector
If it is a vertical vector then why are you using sortrows() instead of sort() ?

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by