Product Support
1103 - What Is the EVAL Function, When Should I Use It, and How Can I Avoid It?
- What is the EVAL function?
- What problems can occur when I use the EVAL function?
- Example 1: Saving data to incrementally numbered ASCII files
- Example 2: Load data from the ASCII files generated in Example 1
- Example 3: Using EVAL to print to random files
- Example 4: Reassign the contents of a variable
- Example 5: Evaluate a MATLAB command
- Example 6: Converting a numeric string to its numeric value
- Example 7: Performing error handling
- Closing remarks on the examples
- Functions similar to EVAL
What is the EVAL function?
- Loading and saving files with variable filenames
- Executing system commands using the ! command
- Executing arbitrary commands stored in a string variable
What problems can occur when I use the EVAL function?
Since EVAL is so powerful, it is easy to misuse the function. In a way, the EVAL function is a lot like global variables; both are tools that can be so useful, it is easier to use them than to search for a more elegant solution. There is a major drawback to the EVAL function, although it can be avoided if you use EVAL carefully.
EVAL can be used to alter arbitrary variables. In addition, two related functions which will be described in Section 11, EVALIN and ASSIGNIN, can be used to alter variables in different function workspaces. These functions can create bugs which are difficult to reproduce and nearly impossible to eliminate.
EVAL is not part of the Embedded MATLAB Subset and as such can not be used when generating C code. When using the MATLAB Compiler, functions that are called explicitly from your main MATLAB file are automatically included by MATLAB Compiler; however, functions that are not explicitly called, for example through EVAL, need to be included at compilation using the -a switch of the mcc command.
Below are some basic examples of how to use EVAL, along with examples which avoid using EVAL but perform the same tasks. These examples will provide you with the ability to create just about any expression in MATLAB.
Example 1: Saving data to incrementally numbered ASCII files
EVAL CODE:
rootname = 'file'; % Root filename extension = '.dat'; % Extension for the files % The following loop concatenates the root filename, % an integer value, and the extension to create the % file in which the data is saved. for data = 1:10 filename = [rootname, num2str(data), extension]; eval(['save ', filename , ' data -ascii']) end
%Use the functional form of SAVE rootname = 'file'; % Root filename extension = '.dat'; % Extension for the files % The following loop concatenates the root filename, % an integer value, and the extension to create the % file in which the data is saved. for data = 1:10 filename = [rootname, int2str(data), extension]; save(filename,'data','-ascii') end
Example 2: Load data from the ASCII files generated in Example 1
rootname = 'file'; % Root filename extension = '.dat'; % Extension of the files % The following loop concatenates the root filename, % an integer value, and the extension to create the % file to be loaded. for data = 1:10 variable = [rootname, int2str(data)]; filename = [variable, extension]; eval(['load ', filename]) eval(['data', num2str(data), ' = ', variable, ';']) eval(['clear ', variable]) end
This section of code has slightly different functionality from the previous.
rootname = 'file'; % Root filename extension = '.dat'; % Extension of the files %Here we assign all of the values loaded into the %array called "var". This allows us to avoid the %EVAL commands. for data = 1:10 filename = [rootname,num2str(data), extension]; variable = load(filename); var(data) = variable; clear variable end
Example 3:Using EVAL to print to random files
rootname = 'fig'; % Root filename for x = 1:10 figure(x) plot(rand(x)) % Random plot filename = [rootname, int2str(x)]; % Concatenate the % root filename and % the integer. eval(['print -dps ',filename]) % Print to the file % using EVAL end
%Use the functional form of PRINT rootname = 'fig'; % Root filename for x = 1:10 figure(x) plot(rand(x)) % Random plot filename = [rootname, int2str(x)]; % Concatenate the % root filename and % the integer. print(filename,'-dps') % Print to the file % w/o using EVAL end
Example 4: Reassign the contents of a variable
In this case, you are prompted to enter the name of a variable. In order to use the data inside the MATLAB file, you must assign the contents of the unknown variable to a known variable. This is an instance where the EVAL function is the only sensible way to code this.
Note that this is a very dangerous example. If the user entered the string "clear all" when the INPUT statement asks for a variable name, all the variables in the MATLAB workspace will be cleared. As Example 5 shows below, any MATLAB command can be executed in this manner. Unless you trust your users not to use commands like EXIT, CLEAR ALL", or the like, you may want to use the EXIST function to test that the string you want to evaluate is the name of a variable in the workspace.
var = magic(10);
<----------------- fun1.m ----------------->
% Enter 'var' as the variable name.
variablename = input('Enter the name of the variable: ','s');
a = eval(variablename); % Reassign the contents of
% variablename to a.
b = 2*a;
mesh(b)
Example 5: Evaluate a MATLAB command
This example generates a Bode plot using a numerator and a denominator you enter.
num = input('Enter the numerator: ');
den = input('Enter the denominator: ');
eval(['bode(',mat2str(num),',',mat2str(den),')'])
%Use FEVAL
fun1 = 'bode';
num = input('Enter the numerator: ');
den = input('Enter the denominator: ');
feval(fun1,num,den)
Example 6: Converting a numeric string to its numeric value
There are two functions you can call to convert a numeric string to its numeric value: STR2NUM and STR2DOUBLE. STR2NUM uses EVAL and evaluates the string to get a numeric value, it can also convert strings containing matrices. STR2DOUBLE does not evaluate the input argument and can only convert a string representation of a scalar value or multiple string representations in a cell array. For example, the function call "str2num('1/2')" evaluates the expression to '0.5000'. STR2DOUBLE cannot convert '1/2' to a numeric value. Because STR2DOUBLE does not evaluate the string, it is much faster.
Example 7: Performing error handling
eval('B = A','disp(''A is undefined'')')
contains two inputs. The underlying concept here is that EVAL will try the first input, and if an error is detected, it will then use the second input. This method is referenced as eval(<try>,<catch>). The first input, B = A is the primary input which EVAL will attempt to evaluate first. If an error is detected then the second input, disp(''A is undefined''), is evaluated.
% CASE 1: A is not defined
clear all
eval('B = A','disp(''A is undefined'')')
% The message "A is undefined" is displayed
% CASE 2: A is defined
A = 1;
eval('B = A','disp(''A is undefined'')')
% The following is displayed in the command window:
%
% B =
% 1
%Use TRY - CATCH
% CASE 1: A is not defined
clear all
try
B = A
catch
disp('A is undefined')
end
% The message "A is undefined" is displayed
% CASE 2: A is defined
A = 1;
try
B = A
catch
disp('A is undefined')
end
% The following is displayed in the command window:
%
% B =
% 1
Closing remarks on the examples
Example 6 is useful when using editable text blocks for numeric input. Since an editable text block stores its input in its String property, when you do a get(h,'String'), a string is returned. By using EVAL, it is easy to convert the string to the numeric value.
Another important characteristic of EVAL is the single quote ('). Example 7 illustrates this. When a single quote is nested in a string, it must be defined by using two single quotes, ''. Note that this is not a double quote. Keeping track of quotes is extremely important. EVAL is often used to create very complicated expressions, which have many single quotes in a row. For example,
eval('disp(''''''This is a string'''''')')
displays
'This is a string'in the command window.
There is one trap of which you should be aware, which is using the EVAL statement when it is not necessary. For example:
eval(['title(''Plot #', num2str(1), ''')'])
title(['Plot #',num2str(1)])
Functions similar to EVAL
feval('bode',num,den)
eval(['bode(',mat2str(num),',',mat2str(den),')'])
EVALIN is used in the same manner as EVAL, except that it has an additional argument which allows you to specify in which workspace the expression you pass to it should be evaluated. It can be used to pass results from one function to the workspace of the function which called it or to the base MATLAB workspace, which can be useful if you require information from a subfunction for another function.
ASSIGNIN allocates to a variable whose name you specify a certain value. The variable is created (or overwritten) in either the workspace of the function which called the function containing ASSIGNIN or the base workspace. With ASSIGNIN, as with EVAL and EVALIN, it is easy to create very subtle and hard to eliminate bugs by changing values of variables in an entirely different function from the one in which they were created.
file = input('Enter the file name and extension: ','s');
unix(['lpr -Pprinter ',file])
dos(['copy /b ',file', lpt1'])
file = input('Enter the filename and extension: ','s');
eval(['!lpr -Pprinter ',file])
eval(['!copy /b ',file,' lpt1'])