1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML>
<HEAD>
<TITLE>EVAL Evaluate a String
</TITLE>
</HEAD>
<BODY>
<H2>EVAL Evaluate a String
</H2>
<P>
Section: <A HREF=sec_freemat.html> FreeMat Functions </A>
<H3>Usage</H3>
The <code>eval</code> function evaluates a string. The general syntax
for its use is
<PRE>
eval(s)
</PRE>
<P>
where <code>s</code> is the string to evaluate. If <code>s</code> is an expression
(instead of a set of statements), you can assign the output
of the <code>eval</code> call to one or more variables, via
<PRE>
x = eval(s)
[x,y,z] = eval(s)
</PRE>
<P>
Another form of <code>eval</code> allows you to specify an expression or
set of statements to execute if an error occurs. In this
form, the syntax for <code>eval</code> is
<PRE>
eval(try_clause,catch_clause),
</PRE>
<P>
or with return values,
<PRE>
x = eval(try_clause,catch_clause)
[x,y,z] = eval(try_clause,catch_clause)
</PRE>
<P>
These later forms are useful for specifying defaults. Note that
both the <code>try_clause</code> and <code>catch_clause</code> must be expressions,
as the equivalent code is
<PRE>
try
[x,y,z] = try_clause
catch
[x,y,z] = catch_clause
end
</PRE>
<P>
so that the assignment must make sense in both cases.
<H3>Example</H3>
Here are some examples of <code>eval</code> being used.
<PRE>
--> eval('a = 32')
a =
32
--> b = eval('a')
b =
32
</PRE>
<P>
The primary use of the <code>eval</code> statement is to enable construction
of expressions at run time.
<PRE>
--> s = ['b = a' ' + 2']
s =
b = a + 2
--> eval(s)
b =
34
</PRE>
<P>
Here we demonstrate the use of the catch-clause to provide a
default value
<PRE>
--> a = 32
a =
32
--> b = eval('a','1')
b =
32
--> b = eval('z','a+1')
b =
33
</PRE>
<P>
Note that in the second case, <code>b</code> takes the value of 33, indicating
that the evaluation of the first expression failed (because <code>z</code> is
not defined).
</BODY>
</HTML>
|