Programming and Data Types |
String Evaluation
String evaluation adds power and flexibility to the MATLAB language, letting you perform operations like executing user-supplied strings and constructing executable strings through concatenation of strings stored in variables.
eval
The eval
function evaluates a string that contains a MATLAB expression, statement, or function call. In its simplest form, the eval
syntax is
For example, this code uses eval
on an expression to generate a Hilbert matrix of order n
.
Here's an example that uses eval
on a statement.
Constructing Strings for Evaluation
You can concatenate strings to create a complete expression for input to eval
. This code shows how eval
can create 10 variables named P1
, P2
, ...P10
, and set each of them to a different value.
feval
The feval
function differs from eval
in that it executes a function rather than a MATLAB expression. The function to be executed is specified in the first argument by either a function handle or a string containing the function name.
You can use feval
and the input
function to choose one of several tasks defined by M-files. This example uses function handles for the sin
, cos
, and log
functions.
fun = [@sin; @cos; @log]; k = input('Choose function number: '); x = input('Enter value: '); feval(fun(k),x)
Note
Use feval rather than eval whenever possible. M-files that use feval execute faster and can be compiled with the MATLAB Compiler.
|
return | Dates and Times |