Avoiding eval when overloading a function

10 views (last 30 days)
Daniel Shub
Daniel Shub on 29 Aug 2012
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
My simplification has apparently confused people. In this question Jonathan essentially noted that
>> 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
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.

Sign in to comment.

Answers (2)

Jan
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
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"?
Daniel Shub
Daniel Shub on 29 Aug 2012
The original question that I was answering, which addressed a problem that I have had in the past, is how to display a variable which contains an HTML string. The DISPLAY function is built-in so you cannot see the code. Using poorly named variables causes problems.

Sign in to comment.


Sean de Wolski
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?

Categories

Find more on Data Type Conversion in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!