Use eval function with strings containing if clauses and for loops
20 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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!
0 comentarios
Respuestas (2)
Mina Mohaghegh
el 9 de Dic. de 2017
this example works, I believe you can figure out the rest:
eval(char(sprintf('for i=1:2 i \n end ')))
0 comentarios
Michael Doroginizky
el 10 de Mzo. de 2022
>> 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 comentarios
Steven Lord
el 10 de Mzo. de 2022
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]
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!