Override how the value of a user defined class is displayed when it is a field of a structure
8 views (last 30 days)
Show older comments
I have created my own class to act like an enumerated type. I haver overridden the method disp() so when a variable containing that type is displayed in the Command Window it shows something meaningful (specifically, the name of that enumerated value.)
classdef MyEnumeratedType
properties(Constant)
ENUMVAL1 = MyEnumeratedType(1, 'ENUMVAl1');
ENUMVAL2 = MyEnumeratedType(2, 'ENUMVAL2');
ENUMVAL3 = MyEnumeratedType(3, 'ENUMVAL3');
end
properties(Access=private)
ordinal
name
end
methods(Access=private)
function this = MyEnumeratedType(ord, name)
this.ordinal = ord;
this.name = name;
end
end
methods
function disp( this )
disp(this.name);
end
end
end
So when I assign it to a variable in the command window, I get the desired output:
>> x = MyEnumeratedType.ENUMVAL2
x =
ENUMVAL2
So far so good. BUT when I assign a value of type MyEnumeratedType to the field of a structure, the display of that structure doesn't display the value, but only tells me that I have a value of type MyEnumeratedType.
>> mystruct.field1 = 42
mystruct =
field1: 42
>> mystruct.field2 = MyEnumeratedType.ENUMVAL3
mystruct =
field1: 42
field2: [1x1 MyEnumeratedType]
How do I get the value of field2 to show up like it does for the double value in field1?
Question also posted at StackOverflow at http://stackoverflow.com/questions/12846290/override-how-the-value-of-a-user-defined-class-is-displayed-when-it-is-a-field-o
1 Comment
Answers (1)
Daniel Shub
on 11 Oct 2012
I think you would need to overload disp for the struct class.
2 Comments
Matt J
on 11 Oct 2012
You can create your own directory @struct and put a revised definition of the display() method in there. You can also call the builtin version of struct/display using the BUILTIN function to help you overload it. Seems like a lot of work to me, however.
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!