How to return the name (identifier) of the object from the call, inside a method of that class

6 views (last 30 days)
Here is a simple example:
classdef simpleClassA
function obj = simpleClassA(x)
obj.prop1 = x;
objName = whatsMyName?
fprintf('Property prop1 of %s = %g', objName, x)
Then, at the command prompt, I construct an object of simpleClassA by:
Gold = simpleClassA(3.0);
and I expect this to display:
"Property prop1 of Gold = 3.0"
What function is "whatsMyName?" in my constructor method that would give me this result?
When I searched the MATLAB Answers database, the closest thing to what I want is these two links below but not exactly:

Accepted Answer

Walter Roberson
Walter Roberson on 15 Dec 2017
You need the techniques described in to get the text of the executing command, and then parse it to find the variable name.
Keep in mind, though, that it is legal to have multiple statements on the same line:
set(Gold, 'prop1', 3.0); set(Silver, 'prop1', 3.0);
You might find it difficult to figure out which of the two set() you are executing.
Yves on 20 Dec 2017
Thanks, @Walter. You were right; I actually don't need to know the name in the constructor, but once the constructor was called, I could use inputname(1) to capture the name of the object in any method of the class.

Sign in to comment.

More Answers (0)


Find more on Construct and Work with Object Arrays 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!