Avoiding eval when overloading a function
3 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
Jan
2012 年 8 月 29 日
+1: My favorite question of the week, because it uses trivial commands to dig in the underground of the Matlab interpreter.
回答 (2 件)
Jan
2012 年 8 月 29 日
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 件のコメント
Jan
2012 年 8 月 29 日
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
2012 年 8 月 29 日
編集済み: Sean de Wolski
2012 年 8 月 29 日
Perhaps (probably) I'm missing something, but could you just use fprintf?
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!