Matlab method to convert an object to a string

I have an object, Person p; . The following properties: p properties:

 Properties: PersonName: 'John Doe' JobType: [1x1 JobTypes] 

JobType is an object of the JobTypes class that contains the JobTypes enumeration. I want to see JobType: Manager instead of JobType: [1x1 JobTypes] . Any thoughts?

+4
source share
2 answers

I never liked Matlab census classes - too much hassle to my liking. Therefore, I have too little experience to truly understand what is happening here. However, I'm going to try: the enumeration class only matters. This is not a string. Such things as

 J = JobTypes.Manager 

assign an object of class JobTypes variable J , set the value associated with Manager . This value is selected by Matlab internals and will never be displayed to the user. The fact that it displays well as J = Manager on the command line is related to the standard implementations of Matlab disp and display for enumeration classes. I think this method does not work properly in conjunction with calling display from another class.

To get around this, you can define your own display method for your Person :

 classdef Person < handle properties PersonName = 'John Doe' JobType = JobTypes.Manager end methods function display(self) fprintf(... ['Properties:\n',... ' Personname: ''%s''\n',... ' JobType: %s\n'],... self.PersonName,... self.JobType.char); end end end 

JobType.char is a Matlab version of a toString for enumeration classes, so pasting it into fprintf will show the actual string! (for this you need kudos @zagy)

See how Mathworks has implemented display methods for some of its classes to understand how to get references to Superclasses, Methods, Events, etc. on display.

+4
source

To do this, you need to rewrite the display(obj) and disp(obj) methods of your class.

Perhaps these two pages will help: 1 , 2

+2
source

All Articles