matlab中eval函数的用法

最进看大牛程序有一段

eval(['temp(:,:,ori) = bg_r' num2str(r) '{' num2str(ori) '};']);

eval函数是以字符串的形式运行代码

下面是matlab官方的注释:

eval(expression) evaluates the MATLAB code in the string expression. If you use eval within an anonymous function, nested function, or function that contains a nested function, the evaluated expression cannot create a variable.
 

其中一个好处就是假如我要对a1,a2,a3,a4,……,a100分别赋予1,2,3,……,100。这时eval就发挥作用了。

 for i=1:100
     eval(['a' num2str(i) '=' num2str(i)]);
 end

当然还有其他例子,比如批量存数据或图片文件等等。

那么开始提到的例子也就好解释了。

注意eval中的中括号在两个以上字符串出现时一定要有,起连接作用。

如:
input:[‘hello’ ‘world’]

output:helloworld

原文地址:https://www.cnblogs.com/penguins/p/3519361.html