MATLAB Global Variables

Ammar Ali May 13, 2021
MATLAB Global Variables

This tutorial will discuss how to share variables between multiple functions by declaring the variables as global in MATLAB.

Share Variables Between Multiple Functions by Declaring Them as global in MATLAB

If a variable is defined inside a function, it can only be used inside that specific function, and you cannot access or change it from another function. These types of variables are called local variables. If you want to share the variables with multiple functions, you have to define them as global variables. You can access and change the global variables in any function. For example, let’s define two functions with the same global variable and set its value in one function, and get its value from another function so that we know the variable is shared between the two functions. First, define a function with the name set, which sets the value of the variable, and save it using the same name as the function name. See the code below.

function set(val)
global s
s = val;

Now, create another function with the name get to get the value of the variable, which we set in the set function and store this function with the same name as the function name. See the code below.

function x = get
global s
x = s;

Now create another script file and use the below code to test the global variable. It should return the value you stored using the set function. See the code below.

set(100)
x = get

Output:

x =

        100

As you can see in the output, the value we stored using the set function is returned by the get function because the variable is a global variable.

Author: Ammar Ali
Ammar Ali avatar Ammar Ali avatar

Hello! I am Ammar Ali, a programmer here to learn from experience, people, and docs, and create interesting and useful programming content. I mostly create content about Python, Matlab, and Microcontrollers like Arduino and PIC.

LinkedIn Facebook

Related Article - MATLAB Variable