MatLab---变量的作用域

1.在脚本中写入变量的值,在命令行窗口也是可以访问和调用的;两者都可以相互调用;

2.如果在脚本中,变量写在函数中,则在命令行窗口中是不可以访问的;因为变量的作用域在函数内部;

3.函数内部的变量有记忆,即记住上次执行时,变量的值;

function persistentTest
persistent count;
if isempty(count)
count=0;
end
count=count+1;
fprintf('the value of count is %d \n',count);
end

命令行窗口:

>> persistentTest  %第一次执行
the value of count is 1
>> persistentTest  %第二次执行
the value of count is 2
>> persistentTest   %第三次执行
the value of count is 3
>> persistentTest   %第四次执行
the value of count is 4

 

如果想要清除count

命令:clear  persistentTest

4.global变量

当在命令行窗口中输入:

global g
>> g=5

g =

5

脚本中:

function outputGlobalg
global g;
fprintf('g is %d',g);
end

脚本中的函数是可以去访问命令窗口中的变量的;

但是,在脚本中,定义全局变量,却在命令窗口中不可以访问;(我自己实践)

posted @ 2022-04-22 17:14  无敌小金刚  阅读(373)  评论(0)    收藏  举报