Self sorting Object
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaire
per isakson
le 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.
Réponse acceptée
Daniel Shub
le 10 Oct 2011
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.
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!