MATLAB® Expressions

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

eval('string')

For example, this code uses eval on an expression to generate a Hilbert matrix of order n.

t = '1/(m + n - 1)';
for m = 1:k
    for n = 1:k
        a(m,n) = eval(t);
    end
end

Here is an example that uses eval on a statement.

eval('t = clock');

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.

for n = 1:10
    eval(['P', int2str(n), '= n .^ 2'])
end

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)

Shell Escape Functions

It is sometimes useful to access your own C or Fortran programs using shell escape functions. Shell escape functions use the shell escape command ! to make external stand-alone programs act like new MATLAB functions. A shell escape M-function is an M-file that

  1. Saves the appropriate variables on disk.

  2. Runs an external program (which reads the data file, processes the data, and writes the results back out to disk).

  3. Loads the processed file back into the workspace.

For example, look at the code for garfield.m, below. This function uses an external function, gareqn, to find the solution to Garfield's equation.

function y = garfield(a,b,q,r)
save gardata a b q r
!gareqn
load gardata

This M-file

  1. Saves the input arguments a, b, q, and r to a MAT-file in the workspace using the save command.

  2. Uses the shell escape operator to access a C or Fortran program called gareqn that uses the workspace variables to perform its computation. gareqn writes its results to the gardata MAT-file.

  3. Loads the gardata MAT-file described in Using MAT-Files to obtain the results.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS