Override how the value of a user-defined class is displayed when it is a structure field

I created my own class to act as an enumerated type. I redefined the disp () method, so when a variable containing this type is displayed in the command window, it shows something meaningful (in particular, the name of this 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 

Therefore, when I assign it to a variable in the command window, I get the desired result:

 >> x = MyEnumeratedType.ENUMVAL2 x = ENUMVAL2 

So far so good. BUT, when I assign a value of type MyEnumeratedType to the structure field, displaying this structure does not 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 so that it displays the same way as for a double value in field1?

+4
source share
2 answers

The disp method for structures shows the contents of the number and cells of arrays, if they can be written in a string, and information about the class / size otherwise:

 s = struct('a',1,'b',[1 2 3],'c',{{1}},'d',magic(3),'e',[1;2]) s = a: 1 b: [1 2 3] c: {[1]} d: [3x3 double] e: [2x1 double] 

Therefore, to display the value of your enum, you need to overload disp for the structures. To do this, you create the @struct directory in your path and create your own disp method, which we hope will accurately reproduce what Matlab does, but with an exception for your specific class. In short: it is possible, but I would rather not be the one who does it.

+1
source

In this view, http://www.mathworks.com/matlabcentral/fileexchange/48637 trying to recreate the disp function is pretty good. So you can use this for disp.m , which you put in the @struct folder.

-1
source

Source: https://habr.com/ru/post/1439236/


All Articles