我在Matlab中遇到一个非常奇怪的全局变量问题.
通常,当您在为其赋值之前将变量声明为全局变量时,它将保留为空变量.我有一个变量R,我想声明为全局变量.但经过I型clear和global R,在变量列表中R已被设置成1*18阵列,一些零的填充于它的其他号码.
我确实有一些共享全局变量的其他函数和脚本R,但我确保在输入后没有调用任何脚本或函数clear,并且当我global R从提示符输入时变量列表已经为空.

但问题仍然存在.我想我必须对有关全局变量的规则有一些严重的误解.任何人都可以解释为什么会这样吗?
提前致谢.
该clear命令不会清除全局变量.它从本地工作空间中删除变量,但它仍然存在.因此,如果您之前为其分配了一些值,则再次声明它只是"显示"本地范围中的全局变量.你必须使用clear all或clear global.从文件中clear:
如果变量名是全局变量,则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
Run Code Online (Sandbox Code Playgroud)