Skip to content

Instantly share code, notes, and snippets.

@wwarriner
Created March 10, 2020 14:53
Show Gist options
  • Save wwarriner/f189373bf40cc741f6d945165a85e115 to your computer and use it in GitHub Desktop.
Save wwarriner/f189373bf40cc741f6d945165a85e115 to your computer and use it in GitHub Desktop.

The properties function of MATLAB dynamicprops handle classes is not returned in sorted order, and isn't even self-consistent. Multiple class initializations followed by clear classes can return different orders each time. Since R2018b (and maybe earlier) one can do the following to return properties in sorted order.

Add public overrides for properties and fieldnames like below. Technically properties() isn't a method of handle dynamicprops, but this should still work because methods are called before built-ins (https://www.mathworks.com/help/matlab/matlab_prog/function-precedence-order.html).

function value = properties( obj )
    if nargout == 0
        disp( builtin( "properties", obj ) );
    else
        value = sort( builtin( "properties", obj ) );
    end
end
function value = fieldnames( obj )
    value = sort( builtin( "fieldnames", obj ) );
end

Add a matlab.mixin.CustomDisplay superclass and add a protected override like below.

function group = getPropertyGroups( obj )
    props = properties( obj );
    group = matlab.mixin.util.PropertyGroup( props );
end

The CustomDisplay mixin then displays only the group returned by getPropertyGroups() when disp() and display() are called. Since the properties() function called in getPropertyGroups() is the new "override", the group is displayed in sorted order. Hope this helps someone!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment