Self sorting Object
Show older comments
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?
1 Comment
per isakson
on 10 Oct 2011
I think this is a good question and I don't believe The Mathworks meant it to work this way. I tested with R2010b. Searching the Help didn't help me. There should at least be a warning or error message.
Accepted Answer
More Answers (0)
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!