matlab避免用eval的方法
2016-07-05 22:46
363 查看
Alternatives to the eval Function
Why Avoid the eval Function?
Although the evalfunction is very powerful and flexible, it not always the best solution to a programming
problem. Code that calls
evalis often less efficient and more difficult to read and debug than code
that uses other functions or language constructs. For example:
MATLAB® compiles code the first time you run it to enhance performance for future runs. However, because code in an
evalstatement
can change at run time, it is not compiled.
Code within an
evalstatement can unexpectedly create or assign to a variable already in the current
workspace, overwriting existing data.
Concatenating strings within an
evalstatement is often difficult to read. Other language constructs
can simplify the syntax in your code.
For many common uses of
eval, there are preferred alternate approaches, as shown in the following examples.
Variables with Sequential Names
A frequent use of the evalfunction is to create sets of variables such as
A1,
A2,
...,
An,
but this approach does not use the array processing power of MATLAB and is not recommended. The preferred method is to store related data in a single array. If the data sets are of different types or sizes, use a structure or cell array.
For example, create a cell array that contains 10 elements, where each element is a numeric array:
numArrays = 10; A = cell(numArrays,1); for n = 1:numArrays A{n} = magic(n); end
Access the data in the cell array by indexing with curly braces. For example, display the fifth element of
A:
A{5}
ans = 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
The assignment statement
A{n} = magic(n)is more elegant and efficient than this call to
eval:
eval(['A', int2str(n),' = magic(n)']) % Not recommended
For more information, see:
Create a Cell Array
Create a Structure Array
Files with Sequential Names
Related data files often have a common root name with an integer index, such as myfile1.matthrough
myfileN.mat.
A common (but not recommended) use of the
evalfunction is to construct and pass each file name to
a function using command syntax, such as
eval(['save myfile',int2str(n),'.mat']) % Not recommended
The best practice is to use function syntax, which allows you to pass variables as inputs. For example:
currentFile = 'myfile1.mat'; save(currentFile)
You can construct file names within a loop using the
sprintffunction
(which is usually more efficient than
int2str), and then call the
savefunction
without
eval. This code creates 10 files in the current folder:
numFiles = 10; for n = 1:numFiles randomData = rand(n); currentFile = sprintf('myfile%d.mat',n); save(currentFile,'randomData') end
For more information, see:
Command vs. Function Syntax
Import or Export a Sequence of Files
Function Names in Variables
A common use of evalis to execute a function when the name of the function is in a variable string.
There are two ways to evaluate functions from variables that are more efficient than using
eval:
Create function handles with the
@symbol or with the
str2funcfunction.
For example, run a function from a list stored in a cell array:
examples = {@odedemo,@sunspots,@fitdemo}; n = input('Select an example (1, 2, or 3): '); examples{n}()
Use the
fevalfunction.
For example, call a plot function (such as
plot,
bar,
or
pie) with data that you specify at run time:
plotFunction = input('Specify a plotting function: ','s'); data = input('Enter data to plot: '); feval(plotFunction,data)
Field Names in Variables
Access data in a structure with a variable field name by enclosing the expression for the field in parentheses. For example:myData.height = [67, 72, 58]; myData.weight = [140, 205, 90]; fieldName = input('Select data (height or weight): ','s'); dataToUse = myData.(fieldName);
If you enter
weightat the input prompt, then you can find the minimum
weightvalue
with the following command.
min(dataToUse)
ans = 90
For an additional example, see Generate Field
Names from Variables.
Error Handling
The preferred method for error handling in MATLAB is to use a try, catchstatement. For example:
try B = A; catch exception disp('A is undefined') end
If your workspace does not contain variable
A, then this code returns:
A is undefined
Previous versions of the documentation for the
evalfunction include the syntax
eval(expression,catch_expr).
If evaluating the
expressioninput returns an error, then
evalevaluates
catch_expr.
However, an explicit
try/catchis significantly clearer than an implicit catch in an
evalstatement.
Using the implicit catch is not recommended.
相关文章推荐
- MySQL 优化
- Google排名优化的几个影响因素
- 选定虚拟主机 性能凸显优势
- DB2优化(简易版)
- 修改一行代码提升 Postgres 性能 100 倍
- Mysql limit 优化,百万至千万级快速分页 复合索引的引用并应用于轻量级框架
- C#中尾递归的使用、优化及编译器优化
- 对优化Ruby on Rails性能的一些办法的探究
- 优化Ruby脚本效率实例分享
- redis的hGetAll函数的性能问题(记Redis那坑人的HGETALL)
- 推荐Sql server一些常见性能问题的解决方法
- Asp编码优化技巧
- SQL Server误区30日谈 第9天 数据库文件收缩不会影响性能
- 和表值函数连接引发的性能问题分析
- SQLServer 2000 升级到 SQLServer 2008 性能之需要注意的地方之一
- 如何监测和优化OLAP数据库
- mysql -参数thread_cache_size优化方法 小结
- 深入学习SQL Server聚合函数算法优化技巧
- 数据库性能优化三:程序操作优化提升性能
- VBS中的字符串连接的性能问题