MATLAB: Self sorting Object

classhandleMATLABoopsort

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
end
end
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

I don't think you can do this and I am pretty sure you do not want to do this. I think the key piece that you are missing is that the handle corresponds to the object and not to the object array.
You can manipulate one of the objects in the array. This changes that object. You can also manipulate every object in the array. In most cases, you cannot manipulate the array itself.
Your sort function is not operating on any of the objects in the array, but rather directly on the array.