matlab中persistex型的变量
2022/8/25 23:24:12
本文主要是介绍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中被看到和使用,而只能在其函数中被调用。这才是这种变量的诡异之处吧。
这篇关于matlab中persistex型的变量的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-01为什么公共事业机构会偏爱 TiDB :TiDB 数据库在某省妇幼健康管理系统的应用
- 2024-04-26敏捷开发:想要快速交付就必须舍弃产品质量?
- 2024-04-26静态代码分析的这些好处,我竟然都不知道?
- 2024-04-26你在测试金字塔的哪一层?(下)
- 2024-04-26快刀斩乱麻,DevOps让代码评审也自动起来
- 2024-04-262024年最好用的10款ER图神器!
- 2024-04-2203-为啥大模型LLM还没能完全替代你?
- 2024-04-2101-大语言模型发展
- 2024-04-17基于SpringWeb MultipartFile文件上传、下载功能
- 2024-04-14个人开发者,Spring Boot 项目如何部署