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?

18 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 30 Oct 2021
"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 Comments

Sign in to comment.

More Answers (0)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!