matlab: use global variables

Introduction

Global variable (global variable) is a type of variable, different from local variables. If a variable is declared as a global variable, the memory it occupies is global memory, not local work area memory. Therefore, global variables can be accessed and modified by all work areas.

Example understanding

Sharing global variables between functions

Define two function files, setGlobalx and getGlobalx

Code
%设置全局变量的值
function setGlobalx(var)
global x
x=var;
end
%获取全局变量的值
function r=getGlobalx
global x
r=x;
end
%使用全局变量来进行计算
function useGlobax
global x
r=sprintf('使用全局变量x=%f来进行计算',x);  %实际问题中,这里为包含x的计算表达式
disp(r);
end
Output result
>> setGlobalx(22)
>> r=getGlobalx

r =

    22
    
>> useGlobax
使用全局变量x=22.000000来进行计算

Sharing global variables between functions and command lines

Similarly, global variables must be accessed on the command line. Just declare it:
global x

Code

Same as above

Output result
>> x
未定义函数或变量 'x'。
 
>> global x
>> x

x =

    22
Published 47 original articles · Like 33 · Visit 310,000+

Guess you like

Origin blog.csdn.net/kaever/article/details/70257543