Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Why does everyone hate 'eval'?

Subject: Why does everyone hate 'eval'?

From: Johan Carlson

Date: 11 Dec, 2008 18:19:02

Message: 1 of 46

Hey guys!

I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks.

OK, I can see that over-use of eval would create, cool-looking, but totally unreadable and inefficient code.

But, are there any other reasons to hate eval this much?

Good coding style on the one hand, I still see the occasional use of eval as highly motivated.

Comments?

/JC

Subject: Why does everyone hate 'eval'?

From: Adam

Date: 11 Dec, 2008 18:36:03

Message: 2 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrlim$oqo$1@fred.mathworks.com>...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval as highly motivated.
>
> Comments?
>
> /JC

motivated => provided with an incentive
?!?!?

http://www.mathworks.com/support/tech-notes/1100/1103.html

"it is easier to use them than to search for a more elegant solution"
aka learning the language

"These functions can create bugs which are difficult to reproduce and nearly impossible to eliminate."

I've never even attempted to use it myself, but it seems it would create unreadable, undebuggable code. If you can't read it and can't fix it what good is it?

~Adam

Subject: Why does everyone hate 'eval'?

From: Joerg Buchholz

Date: 11 Dec, 2008 18:40:18

Message: 3 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrlim$oqo$1@fred.mathworks.com>...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval as highly motivated.
>
> Comments?
>
> /JC

http://blogs.mathworks.com/loren/2005/12/28/evading-eval/

Subject: Why does everyone hate 'eval'?

From: Adam

Date: 11 Dec, 2008 18:41:01

Message: 4 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrlim$oqo$1@fred.mathworks.com>...
 
> But, are there any other reasons to hate eval this much?

Also, 4 & 5
http://www.mathworks.com/matlabcentral/newsreader/view_thread/238471#608347

~Adam

Subject: Why does everyone hate 'eval'?

From: Steven Lord

Date: 11 Dec, 2008 19:12:19

Message: 5 of 46


"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message
news:ghrlim$oqo$1@fred.mathworks.com...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT
> USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but
> totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval
> as highly motivated.
>
> Comments?

Others have posted their own reasons, but one additional reason is that it
can be dangerous. If one of the cases where you think eval would be "highly
motivated" is something like:


function y = evaluateAtXequals5(equationString)
x = 5;
y = eval(equationString);


to evaluate a user-entered expression at x = 5 ... you're giving your user a
loaded weapon and trusting that they will only fire it at the target you've
set up. That trust may be betrayed, either through malice or by accident.
I'm sure you can come up with a 'payload' for this function that could cause
some havoc and/or destruction (remember SYSTEM works inside an EVAL, BTW.)

Now the reason I suggest that users not do something like:

for k = 1:10
    eval(sprintf('a%d = 1;', k));
end

is that it's IMO much harder to read than:

for k = 1:10
    a(k) = 1;
end

or:

a = ones(1, 10);

With the last two, it's obvious upon looking at the code that we're working
with a variable a, and it doesn't take much longer to work out that a will
be a 10-element vector at the end of the code. With the first code, it'll
take longer to figure out that it's creating 10 variables, a1 through a10.

--
Steve Lord
slord@mathworks.com

Subject: Why does everyone hate 'eval'?

From: Johan Carlson

Date: 11 Dec, 2008 19:29:02

Message: 6 of 46

"Steven Lord" <slord@mathworks.com> wrote in message <ghromj$f8g$1@fred.mathworks.com>...
>
> "Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message
> news:ghrlim$oqo$1@fred.mathworks.com...
> > Hey guys!
> >
> > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT
> > USE EVAL!!!!' in various posts during the past few weeks.
> >
> > OK, I can see that over-use of eval would create, cool-looking, but
> > totally unreadable and inefficient code.
> >
> > But, are there any other reasons to hate eval this much?
> >
> > Good coding style on the one hand, I still see the occasional use of eval
> > as highly motivated.
> >
> > Comments?
>
> Others have posted their own reasons, but one additional reason is that it
> can be dangerous. If one of the cases where you think eval would be "highly
> motivated" is something like:
>
>
> function y = evaluateAtXequals5(equationString)
> x = 5;
> y = eval(equationString);
>
>
> to evaluate a user-entered expression at x = 5 ... you're giving your user a
> loaded weapon and trusting that they will only fire it at the target you've
> set up. That trust may be betrayed, either through malice or by accident.
> I'm sure you can come up with a 'payload' for this function that could cause
> some havoc and/or destruction (remember SYSTEM works inside an EVAL, BTW.)
>
> Now the reason I suggest that users not do something like:
>
> for k = 1:10
> eval(sprintf('a%d = 1;', k));
> end
>
> is that it's IMO much harder to read than:
>
> for k = 1:10
> a(k) = 1;
> end
>
> or:
>
> a = ones(1, 10);
>
> With the last two, it's obvious upon looking at the code that we're working
> with a variable a, and it doesn't take much longer to work out that a will
> be a 10-element vector at the end of the code. With the first code, it'll
> take longer to figure out that it's creating 10 variables, a1 through a10.
>
> --
> Steve Lord
> slord@mathworks.com
>

Thanks everyone!
I read most of the threads you linked before, and I agree that readability and efficiency should be put before the lazy way out (using eval).

Now, if everything could be done without eval, why is it still there?

In previous versions of MATLAB, before cell arrays etc. there were some cases that became really complicated (thus rendering much less readable code), but nowadays, maybe the function is not necessary anymore.

The security issue is a good point!

/JC

Subject: Why does everyone hate 'eval'?

From: Bruno Luong

Date: 11 Dec, 2008 19:41:02

Message: 7 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrplu$4in$1@fred.mathworks.com>...

>
> Now, if everything could be done without eval, why is it still there?
>

Like lazy people, they are always there.

Bruno

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 11 Dec, 2008 20:15:05

Message: 8 of 46


The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.

Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.

Subject: Why does everyone hate 'eval'?

From: Bruno Luong

Date: 11 Dec, 2008 20:32:03

Message: 9 of 46

"Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
>
> Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules,

Hi Matt,

Can you elaborate? I do not know that.

Thanks

I also found one case where eval is useful: evaluate a user's enter string expression like a calculator, abusing Matlab parser instead of writing my own. You could argue this is no a lazy attitude, and I admit it is.

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 11 Dec, 2008 20:53:03

Message: 10 of 46

"Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
>
> The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.
>
> Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.
>
>

For example, if I tried to evaluate this,

A{i}=SomeObject;

using subsasgn() as follows

S=substruct('{}',{i});
A=subsasgn(A,S,SomeObject);

then it may produce non-equivalent behavior because in the 2nd instance the subsasgn() method of class(SomeObject) will be called.
It takes precedence over the built-in subsasgn methods for @cell types.

However, what does one do if S is in some way dynmically varying?

Maybe I'm running assignments to A in a loop and in one instance S is as above but in later iterations of the loop I have any or both of the following

S=substruct('{}',{i},'{}',{j})
S=substruct('{}',{i,j})

The only solution I've ever been able to find is to derive an indexing expression for each such S in string form and execute it using eval().

If I'm missing a basic alternative though, I welcome advice...

Subject: Why does everyone hate 'eval'?

From: Steve Amphlett

Date: 11 Dec, 2008 21:03:03

Message: 11 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrlim$oqo$1@fred.mathworks.com>...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval as highly motivated.
>
> Comments?
>
> /JC


I still use eval when building commands to pass to system. Once I'm happy that the command string (echoed sans semicolon) isn't going to cause damage (nasal demons, etc), I'll then uncomment the following system(command) function.

Subject: Why does everyone hate 'eval'?

From: Budias Aao

Date: 11 Dec, 2008 21:57:02

Message: 12 of 46


> Now, if everything could be done without eval, why is it still there?

One of the reasons why is because, despite being considered doomed,
Matlab still uses it alot.
Take, for examle, the spline toolbox and do a grep for eval on the .m files

Subject: Why does everyone hate 'eval'?

From: Oliver Woodford

Date: 11 Dec, 2008 22:08:02

Message: 13 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrlim$oqo$1@fred.mathworks.com>...
> Hey guys!
>
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks.
>
> OK, I can see that over-use of eval would create, cool-looking, but totally unreadable and inefficient code.
>
> But, are there any other reasons to hate eval this much?
>
> Good coding style on the one hand, I still see the occasional use of eval as highly motivated.
>
> Comments?
>
> /JC

I use eval to append the current solution of an iterative program to a mat file.
E.g.
varname = ['A' num2str(iter)];
eval([varname ' = A;']);
save('progress.mat', '-append', varname);
clear(varname);

Obviously A is sufficiently large that I don't want to store lots of variations of it in memory. I don't see any way of achieving the above without eval - I'd rather not have a profusion of mat files, though clearly this is an alternative solution. That is the only time I use eval.

Subject: Why does everyone hate 'eval'?

From: Doug Schwarz

Date: 11 Dec, 2008 23:03:22

Message: 14 of 46

In article <ghs302$qm8$1@fred.mathworks.com>,
 "Oliver Woodford" <o.j.woodford.98@cantab.net> wrote:

> "Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message
> <ghrlim$oqo$1@fred.mathworks.com>...
> > Hey guys!
> >
> > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT
> > USE EVAL!!!!' in various posts during the past few weeks.
> >
> > OK, I can see that over-use of eval would create, cool-looking, but totally
> > unreadable and inefficient code.
> >
> > But, are there any other reasons to hate eval this much?
> >
> > Good coding style on the one hand, I still see the occasional use of eval
> > as highly motivated.
> >
> > Comments?
> >
> > /JC
>
> I use eval to append the current solution of an iterative program to a mat
> file.
> E.g.
> varname = ['A' num2str(iter)];
> eval([varname ' = A;']);
> save('progress.mat', '-append', varname);
> clear(varname);
>
> Obviously A is sufficiently large that I don't want to store lots of
> variations of it in memory. I don't see any way of achieving the above
> without eval - I'd rather not have a profusion of mat files, though clearly
> this is an alternative solution. That is the only time I use eval.


You don't need eval to do that. Do this instead:

  A1 = 1;
  save progress.mat A1 % initial save
  for i = 2:10
      varname = sprintf('A%d',i);
      s = struct(varname,i);
      save progress.mat -append -struct s
  end

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.

Subject: Why does everyone hate 'eval'?

From: Doug Schwarz

Date: 11 Dec, 2008 23:08:51

Message: 15 of 46

In article <ghrplu$4in$1@fred.mathworks.com>,
 "Johan Carlson" <Johan.E.Carlson@gmail.com> wrote:

> Thanks everyone!
> I read most of the threads you linked before, and I agree that readability
> and efficiency should be put before the lazy way out (using eval).
>
> Now, if everything could be done without eval, why is it still there?

Backwards compatibility.


> In previous versions of MATLAB, before cell arrays etc. there were some cases
> that became really complicated (thus rendering much less readable code), but
> nowadays, maybe the function is not necessary anymore.
>
> The security issue is a good point!
>
> /JC


If you really need to create variables you can use assignin inside a
function. It should be safer and more readable than eval.

  function assign(varname,value)
  assignin('caller',varname,value)



>> assign('x1',1)
>> x1
x1 =
     1
>>

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.

Subject: Why does everyone hate 'eval'?

From: Roger Stafford

Date: 11 Dec, 2008 23:27:02

Message: 16 of 46

"Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message <ghrplu$4in$1@fred.mathworks.com>...
> ........
> Now, if everything could be done without eval, why is it still there?
> ........

  Johan, I agree with your original assertion in the beginning of this thread: "I still see the occasional use of eval as highly motivated."

  In many of these discussions about the advisability of using the eval command, I notice a strong tendency on the part of at least a few people to transform the undoubtedly correct statement, "the eval instruction is rarely needed" to the stronger but undoubtedly incorrect statement, "the eval instruction should never be used."

  The Mathworks' Product Support article 1103 states that "The EVAL function is one of the most powerful, flexible, and potentially dangerous functions in MATLAB." It also says "There are two major drawbacks to the EVAL function; the former can be avoided if you use EVAL carefully," the former referring to "EVAL can be used to alter arbitrary variables."

  It is important to note that they are definitely not saying to never use eval, but to use it only in cases where it may really be needed in spite of any drawbacks as to efficiency, ease of debugging, etc. Such cases do exist!

  That distinction between 'rarely' and 'never' is very important. To say 'never' would be to advise its complete removal and in my opinion that would be a serious mistake. It would be tantamount to Mathworks saying that they can anticipate every conceivable task that their users could ever possibly face and in none of these would eval ever be advisable. I don't think Mathworks wishes to put themselves in the position of making such a decision for their users.

  Final question. Have I myself ever used eval? Answer: yes. Could I have avoided its use in these cases? Answer: yes, in many of them; no, in others. Would I like being deprived of ever using it? Definitely not!

Roger Stafford

Subject: Why does everyone hate 'eval'?

From: Oliver Woodford

Date: 11 Dec, 2008 23:39:04

Message: 17 of 46

Doug wrote:
> If you really need to create variables you can use assignin inside a
> function. It should be safer and more readable than eval.
>
> function assign(varname,value)
> assignin('caller',varname,value)

Thanks, Doug! I am doubly enlightened. :-)
Oliver

Subject: Why does everyone hate 'eval'?

From: Steven Lord

Date: 12 Dec, 2008 15:57:43

Message: 18 of 46


"Roger Stafford" <ellieandrogerxyzzy@mindspring.com.invalid> wrote in
message news:ghs7k6$993$1@fred.mathworks.com...
> "Johan Carlson" <Johan.E.Carlson@gmail.com> wrote in message
> <ghrplu$4in$1@fred.mathworks.com>...
>> ........
>> Now, if everything could be done without eval, why is it still there?
>> ........
>
> Johan, I agree with your original assertion in the beginning of this
> thread: "I still see the occasional use of eval as highly motivated."
>
> In many of these discussions about the advisability of using the eval
> command, I notice a strong tendency on the part of at least a few people
> to transform the undoubtedly correct statement, "the eval instruction is
> rarely needed" to the stronger but undoubtedly incorrect statement, "the
> eval instruction should never be used."

I'm pretty sure that I'm one of the people that you're thinking of who seem
to perform that transformation, and your point is taken.

In my mind, EVAL is like a chainsaw. Its use should, IMO, be an "advanced
maneuver". It's a useful tool for certain situations, but can be very
dangerous when used in a situation where it's not needed. My goal in
directing people to solutions other than EVAL is to discourage people from
getting in the habit of using the chainsaw when a pair of scissors would do
the job just fine.

> The Mathworks' Product Support article 1103 states that "The EVAL
> function is one of the most powerful, flexible, and potentially dangerous
> functions in MATLAB." It also says "There are two major drawbacks to the
> EVAL function; the former can be avoided if you use EVAL carefully," the
> former referring to "EVAL can be used to alter arbitrary variables."
>
> It is important to note that they are definitely not saying to never use
> eval, but to use it only in cases where it may really be needed in spite
> of any drawbacks as to efficiency, ease of debugging, etc. Such cases do
> exist!

True.

> That distinction between 'rarely' and 'never' is very important. To say
> 'never' would be to advise its complete removal and in my opinion that
> would be a serious mistake. It would be tantamount to Mathworks saying
> that they can anticipate every conceivable task that their users could
> ever possibly face and in none of these would eval ever be advisable. I
> don't think Mathworks wishes to put themselves in the position of making
> such a decision for their users.

No, but ideally you should know how and when to use the scissors and the
Swiss Army knife, and know that they can't solve the situation, before you
pull out the chainsaw.

> Final question. Have I myself ever used eval? Answer: yes. Could I
> have avoided its use in these cases? Answer: yes, in many of them; no, in
> others. Would I like being deprived of ever using it? Definitely not!

And no one is suggesting its removal, for several reasons [backwards
compatibility and the cases where it's necessary, to name two.]

--
Steve Lord
slord@mathworks.com

Subject: Why does everyone hate 'eval'?

From: Matt Fig

Date: 12 Dec, 2008 17:16:03

Message: 19 of 46

I myself don't 'hate' eval, but I find that it is slower than other methods, when they exist. Just as an example, here is a function that is meant to duplicate the output of bsxfun written two ways. They are substantially the same, both grow arrays in a loop and both do a repmatting, but one uses eval and the other doesn't. I find that the eval version is more than 2 times slower, depending on the inputs.






function C = bsxfun3(fun,A,B)
% Duplicates the output of BSXFUN, though not the method. BSXFUN sends one
% column of the arrays into func at a time. This makes only one function
% call, having first expanded the smaller array to match the dimensions of
% the larger. It is recommended to have the number of elements in the
% first argument larger than the number of elements in the second.
%
% Example:
%
% A = reshape(randperm(90),5,6,3);
% B = randperm(6);
% C = bsxfunfig(@rem,A,B)
%
% Author: Matt Fig
%
% Date: 12/3/08

if numel(B)>numel(A)
    A1 = A; % Switcheroo. Recommend this feature not used.
    A = B;
    B = A1;
    clear A1;
end

szA = size(A);
szB = ones(1,length(szA));
sz = size(B); % Find out where to expand B and where not to expand B.
szB(1:length(sz)) = sz;
szA(szB==szA) = 1;

for ii = length(szB):-1:1 % Inlined from repmat.m
    ind = (1:szB(ii));
    subs{ii} = ind(ones(1,szA(ii)),:); %#ok Usually faster than preall.
end

C = feval(fun,A,B(subs{:}));



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%% Alternative method to all the above. %%%%%%%%%%%%%%%
%%%%% Below we use strings and evil eval. --> Much slower than above. %%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% if numel(B)>numel(A)
% A1 = A; % Switcheroo.
% A = B;
% B = A1;
% clear A1;
% end
%
% szA = size(A);
% szB = zeros(1,length(szA));
% sz = size(B); % Need to find out where to expand B and where not to.
% szB(1:length(sz)) = sz;
%
% str = 'B(';
% for ii = 1:length(szA)
% if szA(ii) ~= szB(ii) % sprintf faster than num2str.
% str = [str,'ones(',sprintf('%d',szA(ii)),',1),']; %#ok
% else
% str = [str,':,']; %#ok
% end
% end
% str(end) = ')';
%
% C = feval(fun,A,eval(str));

Subject: Why does everyone hate 'eval'?

From: Roger Stafford

Date: 13 Dec, 2008 01:34:01

Message: 20 of 46

"Steven Lord" <slord@mathworks.com> wrote in message <ghu1ln$pn9$1@fred.mathworks.com>...
> I'm pretty sure that I'm one of the people that you're thinking of who seem
> to perform that transformation, and your point is taken.
>
> In my mind, EVAL is like a chainsaw. Its use should, IMO, be an "advanced
> maneuver". It's a useful tool for certain situations, but can be very
> dangerous when used in a situation where it's not needed. My goal in
> directing people to solutions other than EVAL is to discourage people from
> getting in the habit of using the chainsaw when a pair of scissors would do
> the job just fine.
>
> > The Mathworks' Product Support article 1103 states that "The EVAL
> > function is one of the most powerful, flexible, and potentially dangerous
> > functions in MATLAB." It also says "There are two major drawbacks to the
> > EVAL function; the former can be avoided if you use EVAL carefully," the
> > former referring to "EVAL can be used to alter arbitrary variables."
> >
> > It is important to note that they are definitely not saying to never use
> > eval, but to use it only in cases where it may really be needed in spite
> > of any drawbacks as to efficiency, ease of debugging, etc. Such cases do
> > exist!
>
> True.
>
> > That distinction between 'rarely' and 'never' is very important. To say
> > 'never' would be to advise its complete removal and in my opinion that
> > would be a serious mistake. It would be tantamount to Mathworks saying
> > that they can anticipate every conceivable task that their users could
> > ever possibly face and in none of these would eval ever be advisable. I
> > don't think Mathworks wishes to put themselves in the position of making
> > such a decision for their users.
>
> No, but ideally you should know how and when to use the scissors and the
> Swiss Army knife, and know that they can't solve the situation, before you
> pull out the chainsaw.
>
> > Final question. Have I myself ever used eval? Answer: yes. Could I
> > have avoided its use in these cases? Answer: yes, in many of them; no, in
> > others. Would I like being deprived of ever using it? Definitely not!
>
> And no one is suggesting its removal, for several reasons [backwards
> compatibility and the cases where it's necessary, to name two.]
> --
> Steve Lord
> slord@mathworks.com

  Hello Steve. Yes, I agree that eval can be a loose cannon in the wrong hands, and no, I didn't have you particularly in mind as making the "transformation" I mentioned. It seems clear from your words that you were only warning people of its drawbacks in the absence of a pressing need to use the instruction. I am relieved to hear that Mathworks has no plans to get rid of it.

  Somehow I am reminded of the time I wrote some assembly language code pertaining to selective memory access on one of my company's machines, and it contained a bug that resulted in the code itself becoming inaccessible as it was running. Now there was a truly dangerous set of instructions! Still, they served an important function if used properly.

Roger Stafford

Subject: Why does everyone hate 'eval'?

From: us

Date: 13 Dec, 2008 02:17:01

Message: 21 of 46

"Johan Carlson"
> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks...

these lovely people are absolutely correct - and - let me add this, after having used ML for 26 years - there is absolutely NO evil eval, which you cannot possibly replace by a genuine string of ML commands or stock functions...

us

Subject: Why does everyone hate 'eval'?

From: Roger Stafford

Date: 13 Dec, 2008 05:10:19

Message: 22 of 46

"us " <us@neurol.unizh.ch> wrote in message <ghv5ut$fj7$1@fred.mathworks.com>...
> "Johan Carlson"
> > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks...
>
> these lovely people are absolutely correct - and - let me add this, after having used ML for 26 years - there is absolutely NO evil eval, which you cannot possibly replace by a genuine string of ML commands or stock functions...
>
> us

  I was afraid I might stir up a reaction from you on this point, Urs. More than once in this newsgroup you have pointed out to me, and rightly so, a use I had made of 'eval' that was not well-advised. Still, I do not accept unreservedly your statement that "these lovely people are absolutely correct" in reference to never using 'eval'. I would like to reserve the right to use it when the situation seems appropriate (and even a few where it is inappropriate.)

  I grant you the validity of your claim that 'eval' CAN always be replaced by other more standard code, but that doesn't necessarily imply that it SHOULD be in every case. To claim that there is always a better way than using 'eval' no matter what the problem is would be a much stronger statement but one I disagree with. There are simply too many conceivable computing tasks that could be devised by the resourceful human brain to be sure of such a claim, in my opinion.

Roger Stafford

Subject: Why does everyone hate 'eval'?

From: Fifo

Date: 13 Dec, 2008 05:27:01

Message: 23 of 46

 
> I grant you the validity of your claim that 'eval' CAN always be replaced by other more standard code, but that doesn't necessarily imply that it SHOULD be in every case. To claim that there is always a better way than using 'eval' no matter what the problem is would be a much stronger statement but one I disagree with. There are simply too many conceivable computing tasks that could be devised by the resourceful human brain to be sure of such a claim, in my opinion.
>
> Roger Stafford


It is tranquilizing to hear voices of wisdom

Subject: Why does everyone hate 'eval'?

From: Bruno Luong

Date: 13 Dec, 2008 07:35:07

Message: 24 of 46

"us " <us@neurol.unizh.ch> wrote in message <ghv5ut$fj7$1@fred.mathworks.com>...
>
>there is absolutely NO evil eval, which you cannot possibly replace by a genuine string of ML commands or stock functions...

I mostly agree with us (for 99% of situations one can replace EVAL).

And when it is possible, I feel much better NOT using it for two reasons:
- readability of the code
- I illustrate the second reason with a somewhat exagerated semaphore: A car is better controlled directly by a conductor (stock function), rather than a person who can see the road and telling a blind conductor what to do (eval): It is slower and not very safe.

Bruno

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 13 Dec, 2008 12:25:03

Message: 25 of 46


> these lovely people are absolutely correct - and - let me add this, after having used ML for 26 years - there is absolutely NO evil eval, which you cannot possibly replace by a genuine string of ML commands or stock functions...


But it may be a long and awkward string of commands, as I and other posters have shown in our examples above.

Subject: Why does everyone hate 'eval'?

From: ?yvind

Date: 13 Dec, 2008 16:16:02

Message: 26 of 46

"us " <us@neurol.unizh.ch> wrote in message <ghv5ut$fj7$1@fred.mathworks.com>...
> "Johan Carlson"
> > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO NOT USE EVAL!!!!' in various posts during the past few weeks...
>
> these lovely people are absolutely correct - and - let me add this, after having used > ML for 26 years - there is absolutely NO evil eval, which you cannot possibly replace >by a genuine string of ML commands or stock functions...
>
> us

Then maybe you can help me out.

I have the name of a Matlab class stored in a string variable, S. I would like to construct a metaclass object for the class named in the variable, S. Right now I'm doing
>> mc = eval(['?',S]);
or,
>> mc = metaclass(eval(s));

How can I avoid using eval here? Mathwork support has been unable to help me.

NB! Note that in the 2008a-documentation it says that you can do
>> mc = metaclass(S);
This is wrong and has been corrected in the newer documentation.

?yvind

Subject: Why does everyone hate 'eval'?

From: Praetorian

Date: 13 Dec, 2008 17:53:45

Message: 27 of 46

On Dec 13, 9:16=A0am, "?yvind" <oyv...@gmail.com> wrote:
> "us " <u...@neurol.unizh.ch> wrote in message <ghv5ut$fj...@fred.mathwork=
s.com>...
> > "Johan Carlson"
> > > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, =
=A0DO NOT USE EVAL!!!!' in various posts during the past few weeks...
>
> > these lovely people are absolutely correct - and - let me add this, aft=
er having used > ML for 26 years - there is absolutely NO evil eval, which =
you cannot possibly replace >by a genuine string of ML commands or stock fu=
nctions...
>
> > us
>
> Then maybe you can help me out.
>
> I have the name of a Matlab class stored in a string variable, S. I would=
 like to construct a metaclass object for the class named in the variable, =
S. Right now I'm doing
>
> >> mc =3D eval(['?',S]);
> or,
> >> mc =3D metaclass(eval(s));
>
> How can I avoid using eval here? Mathwork support has been unable to help=
 me.
>
> NB! Note that in the 2008a-documentation it says that you can do>> mc =3D=
 metaclass(S);
>
> This is wrong and has been corrected in the newer documentation.
>
> ?yvind

>> version

ans =3D

7.7.0.471 (R2008b)

>> s =3D 'memmapfile';
>> m =3D metaclass(['?', s])

m =3D

  meta.class handle
  Package: meta

  Properties:
                   Name: 'char'
            Description: ''
    DetailedDescription: ''
                 Hidden: 0
                 Sealed: 1
        ConstructOnLoad: 1
        InferiorClasses: {0x1 cell}
             Properties: {[1x1 meta.property]}
                Methods: {136x1 cell}
                 Events: {0x1 cell}
           SuperClasses: {0x1 cell}
      ContainingPackage: {}

  Methods, Events, Superclasses

Subject: Why does everyone hate 'eval'?

From: ?yvind

Date: 13 Dec, 2008 23:03:02

Message: 28 of 46

Praetorian <ashish.sadanandan@gmail.com> wrote in message <4b2672cf-f966-4714-a857-82abaa812e6d@z27g2000prd.googlegroups.com>...
> > Then maybe you can help me out.
> >
> > I have the name of a Matlab class stored in a string variable, S. I would=
> like to construct a metaclass object for the class named in the variable, =
> S. Right now I'm doing
> >
> > >> mc =3D eval(['?',S]);
> > or,
> > >> mc =3D metaclass(eval(s));
> >
> > How can I avoid using eval here? Mathwork support has been unable to help=
> me.
> >
> > NB! Note that in the 2008a-documentation it says that you can do>> mc =3D=
> metaclass(S);
> >
> > This is wrong and has been corrected in the newer documentation.
> >
> > ?yvind
>
> >> version
>
> ans =3D
>
> 7.7.0.471 (R2008b)
>
> >> s =3D 'memmapfile';
> >> m =3D metaclass(['?', s])
>
> m =3D
>
> meta.class handle
> Package: meta
>
> Properties:
> Name: 'char'
> Description: ''
> DetailedDescription: ''
> Hidden: 0
> Sealed: 1
> ConstructOnLoad: 1
> InferiorClasses: {0x1 cell}
> Properties: {[1x1 meta.property]}
> Methods: {136x1 cell}
> Events: {0x1 cell}
> SuperClasses: {0x1 cell}
> ContainingPackage: {}
>
> Methods, Events, Superclasses

Is this an answer to my question? As you can see for yourself your approach doesn't work, like I said.

?yvind

Subject: Why does everyone hate 'eval'?

From: Doug Schwarz

Date: 14 Dec, 2008 02:03:02

Message: 29 of 46

In article <gi0n41$ap4$1@fred.mathworks.com>,
 "?yvind" <oyvist@gmail.com> wrote:

> "us " <us@neurol.unizh.ch> wrote in message
> <ghv5ut$fj7$1@fred.mathworks.com>...
> > "Johan Carlson"
> > > I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO
> > > NOT USE EVAL!!!!' in various posts during the past few weeks...
> >
> > these lovely people are absolutely correct - and - let me add this, after
> > having used > ML for 26 years - there is absolutely NO evil eval, which you
> > cannot possibly replace >by a genuine string of ML commands or stock
> > functions...
> >
> > us
>
> Then maybe you can help me out.
>
> I have the name of a Matlab class stored in a string variable, S. I would
> like to construct a metaclass object for the class named in the variable, S.
> Right now I'm doing
> >> mc = eval(['?',S]);
> or,
> >> mc = metaclass(eval(s));
>
> How can I avoid using eval here? Mathwork support has been unable to help me.
>
> NB! Note that in the 2008a-documentation it says that you can do
> >> mc = metaclass(S);
> This is wrong and has been corrected in the newer documentation.
>
> ?yvind


  mc = meta.class.fromName(S);

--
Doug Schwarz
dmschwarz&ieee,org
Make obvious changes to get real email address.

Subject: Why does everyone hate 'eval'?

From: Praetorian

Date: 14 Dec, 2008 02:10:18

Message: 30 of 46

On Dec 13, 4:03=A0pm, "?yvind" <oyv...@gmail.com> wrote:
> Praetorian <ashish.sadanan...@gmail.com> wrote in message <4b2672cf-f966-=
4714-a857-82abaa812...@z27g2000prd.googlegroups.com>...
> > > Then maybe you can help me out.
>
> > > I have the name of a Matlab class stored in a string variable, S. I w=
ould=3D
> > =A0like to construct a metaclass object for the class named in the vari=
able, =3D
> > S. Right now I'm doing
>
> > > >> mc =3D3D eval(['?',S]);
> > > or,
> > > >> mc =3D3D metaclass(eval(s));
>
> > > How can I avoid using eval here? Mathwork support has been unable to =
help=3D
> > =A0me.
>
> > > NB! Note that in the 2008a-documentation it says that you can do>> mc=
 =3D3D=3D
> > =A0metaclass(S);
>
> > > This is wrong and has been corrected in the newer documentation.
>
> > > ?yvind
>
> > >> version
>
> > ans =3D3D
>
> > 7.7.0.471 (R2008b)
>
> > >> s =3D3D 'memmapfile';
> > >> m =3D3D metaclass(['?', s])
>
> > m =3D3D
>
> > =A0 meta.class handle
> > =A0 Package: meta
>
> > =A0 Properties:
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0Name: 'char'
> > =A0 =A0 =A0 =A0 =A0 =A0 Description: ''
> > =A0 =A0 DetailedDescription: ''
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0Hidden: 0
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0Sealed: 1
> > =A0 =A0 =A0 =A0 ConstructOnLoad: 1
> > =A0 =A0 =A0 =A0 InferiorClasses: {0x1 cell}
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0Properties: {[1x1 meta.property]}
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 Methods: {136x1 cell}
> > =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0Events: {0x1 cell}
> > =A0 =A0 =A0 =A0 =A0 =A0SuperClasses: {0x1 cell}
> > =A0 =A0 =A0 ContainingPackage: {}
>
> > =A0 Methods, Events, Superclasses
>
> Is this an answer to my question? As you can see for yourself your approa=
ch doesn't work, like I said.
>
> ?yvind

What do you mean it doesn't work? I retrieved the metaclass
information for a class whose name was stored in a string variable
without using EVAL. Isn't that what you wanted? Anyway, Doug has a
solution that doesn't even require string concatenation.

Subject: Why does everyone hate 'eval'?

From: ?yvind

Date: 14 Dec, 2008 08:00:07

Message: 31 of 46

Praetorian <ashish.sadanandan@gmail.com> wrote in message <9e91603f-17c3-4e81-ad47-33379c3e8b95@p2g2000prf.googlegroups.com>...
> > Is this an answer to my question? As you can see for yourself your approa=
> ch doesn't work, like I said.
> >
> > ?yvind
>
> What do you mean it doesn't work? I retrieved the metaclass
> information for a class whose name was stored in a string variable
> without using EVAL. Isn't that what you wanted? Anyway, Doug has a
> solution that doesn't even require string concatenation.

No, you retrieved a metaclass object for the 'char' class. This is the expected behaviour when you input a string to metaclass(). Compare the output of
>> metaclass('?memmapfile')
to
>> ?memmapfile
'?memmapfile' is a char object, that's the point here.

Thanks, Doug! That's the solution. Support told me there was no way around using eval here.

Well, another use of eval knocked down.

?yvind

Subject: Why does everyone hate 'eval'?

From: Praetorian

Date: 14 Dec, 2008 08:37:20

Message: 32 of 46

On Dec 14, 1:00=A0am, "?yvind" <oyv...@gmail.com> wrote:
> Praetorian <ashish.sadanan...@gmail.com> wrote in message <9e91603f-17c3-=
4e81-ad47-33379c3e8...@p2g2000prf.googlegroups.com>...
> > > Is this an answer to my question? As you can see for yourself your ap=
proa=3D
> > ch doesn't work, like I said.
>
> > > ?yvind
>
> > What do you mean it doesn't work? I retrieved the metaclass
> > information for a class whose name was stored in a string variable
> > without using EVAL. Isn't that what you wanted? Anyway, Doug has a
> > solution that doesn't even require string concatenation.
>
> No, you retrieved a metaclass object for the 'char' class. This is the ex=
pected behaviour when you input a string to metaclass(). Compare the output=
 of>> metaclass('?memmapfile')
> to
> >> ?memmapfile
>
> '?memmapfile' is a char object, that's the point here.
>
> Thanks, Doug! That's the solution. Support told me there was no way aroun=
d using eval here.
>
> Well, another use of eval knocked down.
>
> ?yvind

Sorry about that, I should learn to read the output more carefully!

Subject: Why does everyone hate 'eval'?

From: Steven Lord

Date: 15 Dec, 2008 15:54:25

Message: 33 of 46


"us " <us@neurol.unizh.ch> wrote in message
news:ghv5ut$fj7$1@fred.mathworks.com...
> "Johan Carlson"
>> I've been running into comments like "NO, NO, NO, WHATEVER YOU DO, DO
>> NOT USE EVAL!!!!' in various posts during the past few weeks...
>
> these lovely people are absolutely correct - and - let me add this, after
> having used ML for 26 years - there is absolutely NO evil eval, which you
> cannot possibly replace by a genuine string of ML commands or stock
> functions...

I don't believe that's correct. One use case that I haven't been able to
think of a way to handle without using EVAL is converting a user-input
string into an anonymous function. [And yes, I filed an enhancement request
for a way to do this, perhaps by enhancing STR2FUNC, back when anonymous
functions were first under development.] This would be useful for working
with the "function functions".


function y = stringToAnonymous(str, vars)
y = eval(['@(' vars ') ' str]);


--
Steve Lord
slord@mathworks.com

Subject: Why does everyone hate 'eval'?

From: Rune Allnor

Date: 15 Dec, 2008 16:33:33

Message: 34 of 46

On 15 Des, 16:54, "Steven Lord" <sl...@mathworks.com> wrote:

> I don't believe that's correct. =A0One use case that I haven't been able =
to
> think of a way to handle without using EVAL is converting a user-input
> string into an anonymous function. =A0

In a previous post you compared EVAL with "handing the user a
loaded weapon" - which I fully agree with. However, I don't
see the difference between 'evil EVAL' as of today and what
you suggest.

Rune

Subject: Why does everyone hate 'eval'?

From: us

Date: 15 Dec, 2008 16:46:42

Message: 35 of 46

"Steven Lord"
> One use case that I haven't been able to
> think of a way to handle without using EVAL is converting a user-input
> string into an anonymous function.

> function y = stringToAnonymous(str, vars)
> y = eval(['@(' vars ') ' str]);

well,...

% the command string
     var='a';
     str='cosd(a)';
     com=sprintf('@(%s) %s',var,str);
% the engine
     tmp=inline(com);
     fh=tmp('anything');
     whos fh
% fh 1x1 16 function_handle
% the application
     fh(60)
% ans = 0.5

note: i never said it was beautiful, i just said it's possible... - and - as was discussed several times in the past: we all hope that STR2FUNC eventually will handle this...
us

Subject: Why does everyone hate 'eval'?

From: us

Date: 15 Dec, 2008 17:02:01

Message: 36 of 46

"us "
> note: i never said it was beautiful, i just said it's possible...

i'm wrong - for this particular construct, INLINE eventually calls EVAL...

us

Subject: Why does everyone hate 'eval'?

From: Darik

Date: 15 Dec, 2008 17:46:02

Message: 37 of 46

"Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrujf$d4d$1@fred.mathworks.com>...
> "Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
> >
> > The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.
> >
> > Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.
> >
> >
>
> For example, if I tried to evaluate this,
>
> A{i}=SomeObject;
>
> using subsasgn() as follows
>
> S=substruct('{}',{i});
> A=subsasgn(A,S,SomeObject);
>
> then it may produce non-equivalent behavior because in the 2nd instance the subsasgn() method of class(SomeObject) will be called.
> It takes precedence over the built-in subsasgn methods for @cell types.
>
> However, what does one do if S is in some way dynmically varying?
>
> Maybe I'm running assignments to A in a loop and in one instance S is as above but in later iterations of the loop I have any or both of the following
>
> S=substruct('{}',{i},'{}',{j})
> S=substruct('{}',{i,j})
>
> The only solution I've ever been able to find is to derive an indexing expression for each such S in string form and execute it using eval().
>
> If I'm missing a basic alternative though, I welcome advice...
>

Just wanted to point out there's the function BUILTIN for this exact reason.

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 15 Dec, 2008 20:18:03

Message: 38 of 46

"Darik" <dgambleDEL@uwaterlooDEL.caDEL> wrote in message <gi654q$sfk$1@fred.mathworks.com>...
> "Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrujf$d4d$1@fred.mathworks.com>...
> > "Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
> > >
> > > The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.
> > >
> > > Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.
> > >
> > >
> >
> > For example, if I tried to evaluate this,
> >
> > A{i}=SomeObject;
> >
> > using subsasgn() as follows
> >
> > S=substruct('{}',{i});
> > A=subsasgn(A,S,SomeObject);
> >
> > then it may produce non-equivalent behavior because in the 2nd instance the subsasgn() method of class(SomeObject) will be called.
> > It takes precedence over the built-in subsasgn methods for @cell types.
> >
> > However, what does one do if S is in some way dynmically varying?
> >
> > Maybe I'm running assignments to A in a loop and in one instance S is as above but in later iterations of the loop I have any or both of the following
> >
> > S=substruct('{}',{i},'{}',{j})
> > S=substruct('{}',{i,j})
> >
> > The only solution I've ever been able to find is to derive an indexing expression for each such S in string form and execute it using eval().
> >
> > If I'm missing a basic alternative though, I welcome advice...
> >
>
> Just wanted to point out there's the function BUILTIN for this exact reason.


Probably worth a try.

I was never sure if builtin() actually works, but that might be because I was trying to use it to overload help(), which is not a .bi file.

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 7 Feb, 2009 15:24:01

Message: 39 of 46


> > "Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
> > >
> > > The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.
> > >
> > > Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.
------------------------------------


"Darik" <dgambleDEL@uwaterlooDEL.caDEL> wrote in message <gi654q$sfk$1@fred.mathworks.com>...
> Just wanted to point out there's the function BUILTIN for this exact reason.
-----------------------------------

Unfortunately, bulitin() is not a perfect solution, since it doesn't seem to handle multiple output arguments very well.

Consider the following structure

v.a={1 2 3};

I will try to get the effect of typing v.a{:} in two different ways, one with eval() and one with builtin():

CASE 1: EVAL


>>s=substruct('.','a','{}',{':'});

>>z='.a{s(2).subs{:}}'

>> eval(['v' z ]) %works fine, same ouput as v.a{:}

ans =

     1


ans =

     2


ans =

     3



CASE 2: BUILTIN

>> builtin('subsref', v,s) %problems with expected number of outputs

ans =

     1


So eval() works where builtin() fails...

Subject: Why does everyone hate 'eval'?

From: Loren Shure

Date: 9 Feb, 2009 15:20:40

Message: 40 of 46

In article <gmk92h$ls9$1@fred.mathworks.com>, xys@whatever.com says...
>
> > > "Matt" <mjacobson.removethis@xorantech.com> wrote in message <ghrsc8$194$1@fred.mathworks.com>...
> > > >
> > > > The one time that I have found eval() indispensible is in creating overloaded subsref/subsasgn methods for classes.
> > > >
> > > > Calling subsref()/subsasgn() by themselves is known to produce unpredictable behavior because of dispatching rules, but if you execute the equivalent expression using eval this tends not to happen.
> ------------------------------------
>
>
> "Darik" <dgambleDEL@uwaterlooDEL.caDEL> wrote in message <gi654q$sfk$1@fred.mathworks.com>...
> > Just wanted to point out there's the function BUILTIN for this exact reason.
> -----------------------------------
>
> Unfortunately, bulitin() is not a perfect solution, since it doesn't seem to handle multiple output arguments very well.
>
> Consider the following structure
>
> v.a={1 2 3};
>
> I will try to get the effect of typing v.a{:} in two different ways, one with eval() and one with builtin():
>
> CASE 1: EVAL
>
>
> >>s=substruct('.','a','{}',{':'});
>
> >>z='.a{s(2).subs{:}}'
>
> >> eval(['v' z ]) %works fine, same ouput as v.a{:}
>
> ans =
>
> 1
>
>
> ans =
>
> 2
>
>
> ans =
>
> 3
>
>
>
> CASE 2: BUILTIN
>
> >> builtin('subsref', v,s) %problems with expected number of outputs
>
> ans =
>
> 1
>
>
> So eval() works where builtin() fails...
>

call builtin with multiple outputs:

[a,b,c] = builtin(....)


--
Loren
http://blogs.mathworks.com/loren

Subject: Why does everyone hate 'eval'?

From: David

Date: 9 Feb, 2009 17:51:01

Message: 41 of 46


the BIGGEST reason everyone hates eval is it starts long discussions like this one!

Subject: Why does everyone hate 'eval'?

From: Matt

Date: 11 Feb, 2009 02:22:02

Message: 42 of 46

Loren Shure <loren@mathworks.com> wrote in message
> > So eval() works where builtin() fails...
> >
>
> call builtin with multiple outputs:
>
> [a,b,c] = builtin(....)
>
>
> --
> Loren
> http://blogs.mathworks.com/loren

This does not duplicate the full effect and utility of the v.a{:} operation because I would have to know in advance how many outputs there will be and to create variables to hold them.

But what if I wanted to use v.a{:} to generate a comma-separated list of input arguments, whose length is dynamically determined?

I clearly cannot do this reliably using builtin() as the folllowing shows

v.a={1 2 3};
 s=substruct('.','a','{}',{':'});

>> [a,b,c]=deal( v.a{:} )

a =

     1


b =

     2


c =

     3


>> [a,b,c]=deal( builtin('subsref', v,s) )

a =

     1


b =

     1


c =

     1

Subject: Why does everyone hate 'eval'?

From: Loren Shure

Date: 11 Feb, 2009 15:07:10

Message: 43 of 46

In article <gmtcoa$rqf$1@fred.mathworks.com>, xys@whatever.com says...
> Loren Shure <loren@mathworks.com> wrote in message
> > > So eval() works where builtin() fails...
> > >
> >
> > call builtin with multiple outputs:
> >
> > [a,b,c] = builtin(....)
> >
> >
> > --
> > Loren
> > http://blogs.mathworks.com/loren
>
> This does not duplicate the full effect and utility of the v.a{:} operation because I would have to know in advance how many outputs there will be and to create variables to hold them.
>
> But what if I wanted to use v.a{:} to generate a comma-separated list of input arguments, whose length is dynamically determined?
>
> I clearly cannot do this reliably using builtin() as the folllowing shows
>
> v.a={1 2 3};
> s=substruct('.','a','{}',{':'});
>

You MAY be able to use nargout(@yourFun) but it will only return the
number of outputs declared when called this way.

--
Loren
http://blogs.mathworks.com/loren

Subject: Why does everyone hate 'eval'?

From: Tim Davis

Date: 17 Feb, 2009 22:03:03

Message: 44 of 46

assignin ('tongue', cheek) ;

Here's a proof of the statement "Eval is not evil". Premise one: The MathWorks is not evil. Premise two: A non-evil organization does not do evil things. Premise three: "eval" appears at least 2,329 times inside MATLAB and its toolboxes, excluding comments:

% grep "\<eval\>" */*/*.m */*/*/*.m */*/*/*/*.m */*/*/*/*/*.m | grep -v "\.m:%" | wc -l
   2329
% pwd
/opt/matlab2008b

Conclusion: eval is not evil.

A more careful count, by stripping all comments and the like, reveals 2,139 calls to eval. Exactly three of them are marked with the M-lint %#ok ... so I guess at least three evals are truly OK. :-)

unassignin ('tongue', cheek) ;

Subject: Why does everyone hate 'eval'?

From: us

Date: 17 Feb, 2009 22:12:01

Message: 45 of 46

"Tim Davis"
> Here's a proof of the statement "Eval is not evil". Premise one: The MathWorks is not evil. Premise two: A non-evil organization does not do evil things. Premise three: "eval" appears at least 2,329 times inside MATLAB and its toolboxes, excluding comments...

conclusion: premises one and two are wrong...

us

Subject: Why does everyone hate 'eval'?

From: us

Date: 26 Feb, 2009 14:45:04

Message: 46 of 46

"Steven Lord"
> "us "
> > ...after having used ML for 26 years - there is absolutely NO evil eval, which you
> > cannot possibly replace by a genuine string of ML commands or stock
> > functions...
>
> I don't believe that's correct. One use case that I haven't been able to
> think of a way to handle without using EVAL is converting a user-input
> string into an anonymous function. [And yes, I filed an enhancement request
> for a way to do this, perhaps by enhancing STR2FUNC, back when anonymous
> functions were first under development.] This would be useful for working
> with the "function functions".
> function y = stringToAnonymous(str, vars)
> y = eval(['@(' vars ') ' str]);

the solution to this (last) conundrum is (finally and officially) given here

http://www.mathworks.com/matlabcentral/newsreader/view_thread/245094

us

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us