Use eval function with strings containing if clauses and for loops

조회 수: 10 (최근 30일)
Enrico
Enrico 2013년 10월 3일
댓글: Steven Lord 2022년 3월 10일
Hi,
this is what I'm trying to do:
  1. Build a string containing code (including a for loop and an if clause)
  2. 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
Mina Mohaghegh 2017년 12월 9일
this example works, I believe you can figure out the rest:
eval(char(sprintf('for i=1:2 i \n end ')))

Michael Doroginizky
Michael Doroginizky 2022년 3월 10일
>> 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
Rik 2022년 3월 10일
Why would you encourage the use of eval by reviving such an old thread?
Steven Lord
Steven Lord 2022년 3월 10일
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]
ans = 2×11
-5 -4 -3 -2 -1 0 1 2 3 4 5 7 7 7 7 10 5 5 5 5 5 5
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]
ans = 3×11
-5 -4 -3 -2 -1 0 1 2 3 4 5 7 7 7 7 10 10 5 5 5 5 5 7 7 7 7 10 10 5 5 5 5 5

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by