Self sorting Object
이전 댓글 표시
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
per isakson
2011년 10월 10일
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.
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!