The Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Use eval() to execute for loops and if clauses
Replies: 4   Last Post: Oct 15, 2013 9:52 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Christopher Creutzig

Posts: 323
Registered: 2/24/09
Re: Use eval() to execute for loops and if clauses
Posted: Oct 4, 2013 8:43 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

On 04.10.13 12:18, Enrico wrote:

> I have a code that writes a string depending on what happened before in the program. The string created is more MATLAB code possibly containing for loops or if clauses.

I think you should seriously consider solving your problem in a
different way. Creating code on they fly is usually not a good idea.

> I want to execute the string as if it were MATLAB code, i tried to use the eval() function but it did not work out.
> A simple example is:
> a=5;
> eval('if a>4 b=1 end');
> MATLAB returns the error:
> Error: Illegal use of reserved keyword "end".

Which is exactly what happens if the string were MATLAB code outside of
eval, so it did just what you said you wanted:

>> a=5;
>> if a>4 b=1 end

if a>4 b=1 end
Error: Illegal use of reserved keyword "end".

Maybe you actually wanted to do something like this instead?

>> if a>4, b=1, end

b =


But again, try not to use eval. Even if you ignore the
debugging/maintaining problems with it, eval will very likely be slower
than other routes to your original problem.



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.