Persistent Memory vs Global Memory in MATLAB

Imagine you have a box where you keep your toys. Sometimes, you want to keep a toy inside the box and take it out later to play again. Persistent memory and global memory in MATLAB are like special boxes that help the computer remember things while running programs.

What is Persistent Memory?

Persistent memory in MATLAB is like a special box inside a toy room. When you play with a toy and put it back in the box, the toy stays there only when you are in that room (inside a specific function in MATLAB). If you leave the room (stop the function) and come back, the toy is still inside the box! But if you start a completely new game or turn off the room, the toys disappear.

In MATLAB, persistent memory is used inside functions with the keyword persistent. It helps the function remember values between its multiple calls without losing them.

What is Global Memory?

Global memory is like a big toy box in a common room that everyone in the house can reach. If you put a toy in this box, anyone can take it out and play with it anytime, no matter which room they are in. And the toy will stay there until you decide to remove it or turn off the house (close MATLAB).

In MATLAB, global memory is created using the global keyword. Variables declared as global can be accessed and changed from any function or script as long as they are declared global there too.

Summary Table

Memory TypeWhere it is usedWho can access itHow long it keeps the data
Persistent MemoryInside one functionOnly that functionBetween calls to that function (does not reset until MATLAB is closed or cleared)
Global MemoryAnywhere in MATLAB (functions or scripts)All functions/scripts that declare it globalUntil MATLAB session ends or variable is cleared

Example to try

Here is a small example to understand persistent memory:

function countCalls()
    persistent count;
    if isempty(count)
        count = 0;
    end
    count = count + 1;
    disp(['Function called ', num2str(count), ' times']);
end

Each time you run countCalls(), it remembers how many times you called it without using global variables!

And here is an example with global memory:

global totalCalls
if isempty(totalCalls)
    totalCalls = 0;
end

function updateTotalCalls()
    global totalCalls
    totalCalls = totalCalls + 1;
    disp(['Total calls: ', num2str(totalCalls)]);
end

Here, totalCalls is shared across different functions and scripts that use global totalCalls.

Hopefully, this helps you understand how persistent and global memories work in MATLAB!


Ask a followup question

Loading...