Avoiding eval when overloading a function
10 views (last 30 days)
Show older comments
I used eval in this answer where I was trying to overload display and it is making me feel sick. Is it possible to avoid the eval? A simple example is overloading display to prepend a string to object of class char ...
If you add the following function to a folder called @char
function display(X)
X = ['The string: ', X];
eval([inputname(1), ' = X;']);
eval(['builtin(''display'', ', inputname(1), ');']);
end
and then do
>> z = 'Hello world'
z =
The string: Hello world
I need the eval to get the variable name correct in the output. The documentation for display shows a work around where you recreate the functionality of the built-in display, but that is more distasteful to me than eval. Is it possible to overload display to do some preprocessing and then hand off the result to the built-in display without using eval
EDIT
>> str = '<test TEST>'
returns
str =
TEST
but he wanted it to return
str =
<test TEST>
I suggested an answer which overloaded display in a manner analogous to my simplification above.
1 Comment
Jan
on 29 Aug 2012
+1: My favorite question of the week, because it uses trivial commands to dig in the underground of the Matlab interpreter.
Answers (2)
Jan
on 29 Aug 2012
I do not get the problem. Would this be useful:
function display(X)
Name = inputname(1);
if ~isempty(Name)
localAssignName(Name, X);
builtin('display', Name);
end
end
function localAssignName(Name, Data)
assignin('caller', Name, ['The string: ', Data]);
end
I cannot test this currently. How does the output differ from your expectations?
3 Comments
Jan
on 29 Aug 2012
Then let me apply a subterfuge: Why on earth do you need such a strange function?!
I'll take a look into the source of DISPLAY in the evening. Obviously it uses inputname itself, such that my approach must fail. What happens with your method, when the variable is called "inputname" or "builtin"?
Sean de Wolski
on 29 Aug 2012
Edited: Sean de Wolski
on 29 Aug 2012
Perhaps (probably) I'm missing something, but could you just use fprintf?
See Also
Categories
Find more on Data Type Conversion 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!