Retrieve an object's name

조회 수: 42 (최근 30일)
Christopher Ison
Christopher Ison 2011년 7월 7일
댓글: Steven Lord 2021년 5월 31일
I've used Matlab a long time (10+ years) but for the life of me I can't do something rather stupidly simple: get an object's name (not its class name but the name of a specific instance). For testing purposes, I just need a function to print out the name of a specific instance of an object. Surely there is a straightforward way to do this that I'm overlooking but it doesn't easily show up in any of the help retrievals I've tried. None of my fellow Matlab users here at work could give me any help. (I know I'm going to be red-faced when I learn (relearn?) the method.)

채택된 답변

Sean de Wolski
Sean de Wolski 2011년 7월 7일
whos
?
x = whos;
idx = cellfun(@(x)strcmp(x,'double'),{x(:).class}); %change 'double' to your class
x(idx).name
  댓글 수: 5
CCC
CCC 2021년 5월 31일
I would like to do that with a method within the instance itself.
If you use evalin for example in 'base' you may overwrite x if exists (can be solved)
but then you get, as Lucas mentioned a list of the same class, you could add a unique property to each instance so that:
Looking for something more elegant!
function charname = getInstanceName(obj)
% Handle this variables as inputs, properties or whatever you want:
yourclass = obj.type; % Any comand that returns your instance's class.
workspaceoftheinstance = 'base';
propertyID = 'Reference'; % Any unique ID of your instance.
% Just a way to avoid using X, looking for a better one, or
% simply use the 'else'.
if ~evalin(workspaceoftheinstance,'exist(''x'')')
evalin(workspaceoftheinstance,'x = whos;');
x = evalin('base','x');
else
evalin(workspaceoftheinstance,...
'super_long_variable_name_nobody_would_use_for_this = whos;');
x = evalin(workspaceoftheinstance,...
'super_long_variable_name_nobody_would_use_for_this');
end
% Same as the Accepted Answer:
idx = cellfun(@(x)strcmp(x,yourclass),{x(:).class});
instances = x(idx);
if length(instances)>1
% We try to solve the list of instances of the same class with the
% unique .Reference property (same solution as Accepted Answer):
for i = 1:length(instances)
if evalin(workspaceoftheinstance,['strcmp(',instances(i).name,'.',propertyID,...
',''',obj.Reference,''')'])
charname = instances(i).name;
obj.varname = instances(i).name;
break
end
end
else
% There's only one.
charname = instances.name;
obj.varname = instances.name;
end
end
Steven Lord
Steven Lord 2021년 5월 31일
IF you're doing this for diagnostic purposes (to include the name of the input in a warning or error message) and not to try to reach into the calling workspace to modify the object and if you're able to handle the scenario where the input has no name use inputname.
x = 1:10;
showInputName(x)
The name of the input is 'x'.
showInputName(1:10)
The input has no name.
function showInputName(in)
s = inputname(1);
if isempty(s)
fprintf("The input has no name.\n")
else
fprintf("The name of the input is '%s'.\n", s)
end
end

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Christopher Ison
Christopher Ison 2011년 7월 8일
Well, I found the short answer and it's really, really stupid:
function namestr = getobjname(obj)
namestr = inputname(1);
So if I type this at the command line:
namestring = getobjname(myobject)
If "myobject" exists, it returns
>>namestring = myobject
which can now be printed in an output display. Very helpful, Mathworks.
  댓글 수: 4
Lucas Schneeberger
Lucas Schneeberger 2020년 4월 1일
편집: Lucas Schneeberger 2020년 4월 1일
Is there a way to get the name of the instance inside the class constructor ? I would like to assign a value to obj.name property during the object construction.
This would require the left part of the assignment as in
instance_name = Class(varargin)
to be already processed when constructing the object, I am not sure if it is the case ...
Steven Lord
Steven Lord 2020년 4월 1일
I would like to assign a value to obj.name property during the object construction.
See the "Initializing Objects in Constructor" section on this documentation page for several examples of how to do this. There's no need to know with what name the class constructor was called to store the output (or even if that output has a name: mycell{1} = myObjectConstructor; is a perfectly valid way to call an object constructor and store the resulting object in a cell in a cell array.)

댓글을 달려면 로그인하십시오.


Paul O'Brien
Paul O'Brien 2018년 11월 13일
In MatLab R2016b, if I have a variable "obj" referring to an object, you can get a list of methods by typing
obj.
and then pressing the tab key. One of the methods is called "string", and
obj.string
yields a string containing the name of the object.
  댓글 수: 1
Steven Lord
Steven Lord 2018년 11월 13일
That assumes that the class author has chosen to overload the string method to behave that way. As an example of where this could fail is the table class:
>> t = array2table(magic(4));
>> class(t)
ans =
'table'
>> string(t)
Error using string
Conversion to string from table is not possible.
This is one case where string(t) and t.string behave differently, but neither gives the name of the variable.
>> t.string
Unrecognized variable name 'string'.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by