Sait
Sait

Reputation: 19815

Matlab method for converting object to string

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

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

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

Upvotes: 4

Views: 3661

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

I have never been fond of enumeration classes in Matlab -- just too much hassle for my taste. Therefore, I have too little experience to truly understand what's going on here. Nevertheless, I'm going to try: an enumeration class only has a value. It is not a string. Things like

J = JobTypes.Manager

will assign a JobTypes class object to the variable J, set to the value associated with Manager. This value is chosen by Matlab's internals, and will never be shown to the user. The fact that it displays nicely as J = Manager on the command line, is due to Matlab's standard disp and display implementations for enumeration classes. I think this method does not work properly in combiation with a call to display from within another class.

To circumvent this, you could 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 Matlab's version of a toString for enumeration classes, so inserting it in fprintf will show the actual string! (kudos to @zagy for this)

Take a look at how the Mathworks has implemented the display methods of some of their own classes to get a feel for how to get the links to Superclasses, Methods, Events, etc. in the display.

Upvotes: 4

denahiro
denahiro

Reputation: 1199

You would need to overwrite the display(obj) and disp(obj) methods of your class to achieve this.

Maybe these two pages help: 1,2

Upvotes: 2

Related Questions