How can I display an enum value in a MATLAB object

Given the following two classes

classdef EnumClass enumeration enumVal1 enumVal2 end end classdef EnumDisplay properties enumValue = EnumClass.enumVal1 numberValue = 1 end end 

When EnumClass displayed, the value is displayed:

 >> E = EnumClass.enumVal1 E = enumVal1 

but when EnumDisplay is displayed in the command window, the enumeration value is suppressed, and only the size and class of the array are displayed.

 >> C = EnumDisplay() C = EnumDisplay with properties: enumValue: [1x1 EnumClass] numberValue: 1 

What is the easiest way to display an enumeration value in a class property list. That is, there is a simple and general way to display a class as follows:

 >> C = EnumDisplay() C = EnumDisplay with properties: enumValue: enumVal1 numberValue: 1 

I suspect this has something to do with inheriting from the matlab.mixin.CustomDisplay class, but I want it to be as general as possible to limit the amount of coding I need to do for each enum class, and / or each a class that has an enumeration value in a property.

Partial solution

I managed to figure out a partial solution to this problem, but it is not entirely satisfactory.

 classdef EnumDisplay < matlab.mixin.CustomDisplay properties enumValue = EnumClass.enumVal1 numberValue = 1 end methods (Access = protected) function groups = getPropertyGroups(This) groups = getPropertyGroups@matlab.mixin.CustomDisplay (This); groups.PropertyList.enumValue = char(This.enumValue); end end end 

Now the display looks like this:

 >> C = EnumDisplay() C = EnumDisplay with properties: enumValue: 'enumVal1' numberValue: 1 

It is almost there, but not quite. I do not want the listed value to be in quotes.

+7
oop enumeration matlab
source share
1 answer

Ok, ok ... this is not the most elegant approach - of course, not as elegant as using matlab.mixin.CustomDisplay - but one of the possibilities is to try to reproduce this functionality yourself, in such a way as to give you more control, That's what I hacked together on the ferry ...

 classdef EnumDisplay properties enumValue = EnumClass.enumVal1 numberValue = 1 end methods function disp(This) cl = class(This) ; fprintf(' <a href="matlab:helpPopup %s">%s</a> with properties: \n\n',cl,cl) ; prop = properties(This) ; len = max(cellfun(@length,prop)) ; for ii = 1:numel(prop) if isnumeric(This.(prop{ii})) fmt = '%g' ; else fmt = '%s' ; end filler = char(repmat(32,1,4+len-length(prop{ii}))) ; fprintf('%s%s: ',filler,prop{ii}) ; fprintf(sprintf('%s \n',fmt),char(This.(prop{ii}))) ; end end end end 

Result:

 >> C = EnumDisplay() C = EnumDisplay with properties: enumValue: enumVal1 numberValue: 1 

Catch only that this may not be completely general, because I may not have used all possible fmt formats. But if you are really desperate, perhaps something like this will work.

0
source share

All Articles