其他分享
首页 > 其他分享> > matlab中persistex型的变量

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

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