我们可以配置 MATLAB let 变量具有最小的局部范围吗?



我们可以配置 MATLAB let 变量具有最小的局部作用域吗?

我想要类似于下面的 matlab 的东西。

% 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

在这个特定示例中,您当然可以使用不同的x0输入调用accum_a函数两次。但是您在文件中定义的每个函数都有自己的本地作用域,因此在错误键入x_0/x0时会导致错误。

最新更新