sigma
sigma

Reputation: 216

MATLAB: Function to display name of class instance (object)

I am stuck with what I expect should be something relatively simple to do. I am writing a class Superclass such that:

 Superclass < handle

and then:

MyClass < Superclass

MyClass contains function DisplayObjectName, which should do what the name suggests. That is, display the name of the class instance (object).

For example, I create an object:

TestObject = MyClass(inputvariable);

Then I would like to have a function such that when I call

TestObject.DisplayObjectName()

the output would be

ans = TestObject

I could not seem to find a way to do that. Any ideas? Any help would be very much appreciated.

Upvotes: 3

Views: 1013

Answers (1)

Pursuit
Pursuit

Reputation: 12345

The inputname function seems to do the trick.

classdef SuperClass < handle
    methods
        function displayObjectName(self)
            disp(inputname(1))
        end
    end
end

Then

classdef MyClass < SuperClass
end 

And

>> TestObject = MyClass;
>> TestObject.displayObjectName
TestObject

Upvotes: 4

Related Questions