Use eval function with strings containing if clauses and for loops
显示 更早的评论
Hi,
this is what I'm trying to do:
- Build a string containing code (including a for loop and an if clause)
- Execute the string as if it were actual code using the eval() function
Example:
a=5;
eval('if a>4 b=1 else b=0 end')
The error displayed is:
Error: Illegal use of reserved keyword "else".
If I remove the else and execute the lines:
a=5;
eval('if a>4 b=1 end')
I get:
Error: Illegal use of reserved keyword "end".
The same error appears if the string contains a for loop.
Is there a way to bypass the problem? Maybe another function I am not aware of?
Thank you!
回答(2 个)
Mina Mohaghegh
2017-12-9
0 个投票
this example works, I believe you can figure out the rest:
eval(char(sprintf('for i=1:2 i \n end ')))
Michael Doroginizky
2022-3-10
0 个投票
>> eval('S=0')
S =
0
>> eval('S=0; for i = 1 : 10 S=S+1; end')
>> S
S =
10
>> eval('S=0; if S > 0 S=5; elseif S < -1 S=7; else S=10; end')
>> S
S =
10
2 个评论
Rik
2022-3-10
Why would you encourage the use of eval by reviving such an old thread?
If you're using eval so you can execute this code inside an anonymous function, for example, you don't need to. Taking a look at the most complicated of the three:
eval('S=0; if S > 0 S=5; elseif S < -1 S=7; else S=10; end')
That could be replaced with a call to discretize (which would have the added benefit of being able to handle a non-scalar S array.)
S = -5:5;
x = discretize(S, [-Inf -1 0 Inf], [7, 10, 5]);
[S; x]
For values of S less than 1 (and greater than or equal to -Inf), the corresponding elements of x are 7. For values greater than or equal to 0 (and less than or equal to Inf) the corresponding elements of x are 5. Otherwise (in this case S = -1) the corresponding elements of x are 10.
If you really need that clause to be strictly greater than, change the 0 in the discretize call to something small but nonzero like eps or eps(0).
x2 = discretize(S, [-Inf -1 eps Inf], [7, 10, 5]);
x3 = discretize(S, [-Inf -1 eps(0) Inf], [7, 10, 5]);
[S; x2; x3]
类别
在 帮助中心 和 File Exchange 中查找有关 Variables 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!