matlab中persistex型的变量
学习matlab中的persistex类型的变量特性和C语言中static型变量差不多。请看代码:
1 %fileName: persistex.m 2 %This script demonstrates persistent variables 3 %The first function has a varibale "count" 4 5 fprintf('This is what happens with a "normal" variable: \n') 6 nopersis 7 nopersis 8 9 %The second function has a persistent varibale "count" 10 fprintf('\nThis is waht happens with a persistent variable: \n') 11 yespersis 12 yespersis
配合nopersis.m:
1 function nopersis 2 %func1 increments a normal varibal "count" 3 %Fromat: func1 or func1() 4 5 count = 0; 6 count = count + 1; 7 fprintf('The value of count is %d\n', count) 8 end
还有yespersis.m:
1 function yespersis 2 %func2 increaments a persistent variable "count" 3 %Forma: func2 or func2() 4 5 persistent count %Declare the variable 6 if isempty(count) 7 count = 0; 8 end 9 count = count + 1; 10 fprintf('The value of count is %d\n', count) 11 end
执行结果:
1 >> persistex 2 This is what happens with a "normal" variable: 3 The value of count is 1 4 The value of count is 1 5 6 This is waht happens with a persistent variable: 7 The value of count is 1 8 The value of count is 2 9 >> persistex 10 This is what happens with a "normal" variable: 11 The value of count is 1 12 The value of count is 1 13 14 This is waht happens with a persistent variable: 15 The value of count is 3 16 The value of count is 4
第1行和第9行不用说了,就是在提示符下,输入脚本名persistex执行脚本
第3行和4行脚本中是调用nopersis函数,由于其中的count变量是local变量,结果都是1
第7行和8行脚本中是调用yespersis函数,由于其中的count变量是persistex变量,前者结果都是1,后者是2
从第9行开始,只是有重新将脚本执行一遍,
第11行和12行是显而易见的为1
第13和和14行是3和4也是可以理解的,明白了了。每次调用,persistex变量都是在前次基础上加1,并保留该值直到下次调用。也就是说,这种变量的声明周期不随着函数调用的结束而消逝,值会一直保存在内存中,因此经过多次的调用才会不停的累加。但是由于该变量count是处于函数yespersis中,该变量并不能在baseworkspace中被看到和使用,而只能在其函数中被调用。这才是这种变量的诡异之处吧。
需要特别注意的是:将变量声明为persistent后,必须用
if ifempty(变量名) 变量名 = 0; end
这样的代码块进行初始化,不能直接赋值,否则,你试试看看就明白了。
但是,想要这种变量归零,可以通过执行指令clear 函数名,此处的函数名是包含persistent变量的函数文件的函数名,这里就应该用:
clear posnum即可清除变量count
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-08-25 你为什么学习效率不高
2017-08-25 Xterm256终端颜色的名称