Learn the difference between persistent memory and global memory in MATLAB with simple explanations and examples perfect for 11-year-olds.
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.
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.
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.
Memory Type | Where it is used | Who can access it | How long it keeps the data |
---|---|---|---|
Persistent Memory | Inside one function | Only that function | Between calls to that function (does not reset until MATLAB is closed or cleared) |
Global Memory | Anywhere in MATLAB (functions or scripts) | All functions/scripts that declare it global | Until MATLAB session ends or variable is cleared |
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!