Is there a way to get an object to sort itself with its own custom sort function?
I have a class right now that is mostly handled in arrays that I would like to sort based on one of its properties. The problem is that the only way to sort the object in the main workspace is to set it equal to the return of the sort function. I would like to be able to simply call sort, and have the object be modified.
Right now it is a handle class, here is a basic template of what I am trying to do.
classdef foo < handle properties prop1; prop2; end methods function obj=foo(varargin) if(nargin==1) obj(varargin{1})=foo; end end function [obj,idx]=sort(obj) [~,idx]=sort([obj.prop1],'descend'); obj=obj(idx); end endend
Most of the error checking has been stripped from my example (along with most of the class). Other posts seem to indicate that calling sort on the object should leave the object sorted, but it doesn't. It returns a sorted object, but the original is always unmodified unless it is implicitly set equal to the return in the workspace (obj=sort(obj)).
Am I missing something able how handles work? Is there a way to get the object to modify itself to be in a new sorted order just by calling one of its own functions?
Best Answer