ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

matlab中persistex型的变量

2022-08-25 15:01:32  阅读:175  来源: 互联网

标签:count 变量 persistex value persistent matlab variable


学习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中被看到和使用,而只能在其函数中被调用。这才是这种变量的诡异之处吧。

标签:count,变量,persistex,value,persistent,matlab,variable
来源: https://www.cnblogs.com/guochaoxxl/p/16624275.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有