我们可以配置MATLAB让变量的局部作用域最小吗?
我想要matlab类似C的东西。
% after some configure ...
for i=1:1:100
a=i*i
end
% here we can not using 'a' any more for it have local scope in for loop.
为什么我要这样,因为整个脚本的作用域有时会导致难以找到错误。
例如:
% get accumulate of b via 100 times of x_0
b=0;
for i=1:1:100
x0=100
b=b+x0
end
% get accumulate of a via 100 times of x_0
a=0
for i=1:1:100
x_0=200
a=a+x0 %mistype x_0 to x0, and hard to find
end
谢谢前进。
我认为没有任何方法可以在脚本/循环中强制使用本地作用域。但是,您可以在单独的文件或同一文件中创建函数。每个函数都有自己的本地作用域。因此,对于您的示例,您可以myScript.m
使用以下内容创建文件:
% get accumulate of b via 100 times of x_0
accum_b(100)
% get accumulate of a via 100 times of x_0
accum_a(200)
function a = accum_a(x0)
a = 0;
for k = 1:100
a = a + x0;
end
end
function b = accum_b(x0)
b = 0;
for k = 1:100
b = b + x0;
end
end
在此特定示例中,您当然可以accum_a
使用不同的x0
输入调用函数两次。但是,您在文件中定义的每个函数都将具有其自己的本地范围,因此,在迷惑时会导致错误x_0/x0
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句