我在Matlab中遇到一个非常奇怪的全局变量问题。
通常,当您在为其指定任何值之前将变量声明为全局变量时,它将保留为空变量。我有一个变量R
,我想将其声明为全局变量。但是在我输入clear
和global R
之后,变量列表R
已经设置为1 * 18数组,其中填充了一些零和其他数字。
我确实有一些共享全局变量R
的其他函数和脚本,但我确保在输入clear
后我没有调用任何脚本或函数,变量列表是我从提示符输入global R
时已经空了。
但问题仍然存在。我想我必须对有关全局变量的规则有一些严重的误解。任何人都可以解释为什么会这样吗?
提前致谢。
答案 0 :(得分:6)
clear
命令不会清除全局变量。它从本地工作空间中删除变量,但它仍然存在。因此,如果您之前为其分配了一些值,则再次声明它只是“显示”本地范围中的全局变量。您必须使用clear all
或clear global
。来自clear
的{{3}}:
如果变量名是全局变量,则clear将其从当前工作空间中删除,但它仍保留在全局工作空间中。
考虑以下示例:
>> clear all;
>> global v;
>> v = 1:100; % assign global variable
>> whos % check if it is there
Name Size Bytes Class Attributes
v 1x100 800 double global
>> clear;
>> whos % nothing declared in local workspace
>> global v;
>> whos % ups, v is not empty!!
Name Size Bytes Class Attributes
v 1x100 800 double global
>> clear global; % you have to clear it properly
>> whos
>> global v % now it is empty
>> whos
Name Size Bytes Class Attributes
v 0x0 0 double global