Clear Filters
Clear Filters

Strange mixup of equally named functions, or persistent variables?

13 views (last 30 days)
Situation is as follows: I have a folder where I develop a library, say MMG_folder, with files:
  1. MMG.m
  2. MMG_example.m
So I develop on MMG.m, run the example to see if things work, all OK. Then:
  1. clear all
  2. clear MMG
I then go to an application folder app_folder which has a copy of MMG.m, and it contains application.m that uses MMG.m. If I type 'which MMG' I get, as expected, app_folder and not MMG_folder. However, when I run application.m I get an error in MMG.m in folder MMG_folder (!) although that folder is not even in the Matlab path. The error indicates something is wrong with a persistent variable in MMG.m.
I could not find answers on this:
  1. Is this known behavior?
  2. Do equally named functions somehow share persistent variables?
Working with Matlab R2023a, I have to restart to get application.m working correctly.

Answers (1)

Divyam
Divyam on 21 Aug 2024 at 9:30
Edited: Divyam on 21 Aug 2024 at 9:32
Hi @Jeroen Boschma, this issue is occuring due to the persistent variables retaining their values and MATLAB caching the functions from the 'MMG.m' file in the 'MMG_folder'. Even though you have a copy of the 'MMG.m' file in the 'app_folder' MATLAB might still be referring to the file in the 'MMG_folder'. In this case the clear function will not reset the persistent variable since the 'MMG_folder' is not on MATLAB path.
This behavior is expected however functions with the same names do not share persistent variables as the variables are specific to the function scope where they were declared.
To overcome this issue, you can follow one of the below troubleshooting steps:
  • Add 'MMG_folder' to MATLAB path and then switch to the 'app_folder'. Now use the 'clear MMG' command.
  • Check whether 'app_folder' is higher than 'MMG_folder' in the MATLAB path hierarchy. To put 'app_folder' at the top of the path hierarchy, use the 'addpath' function. Here is the documentation for the 'addpath' function: https://www.mathworks.com/help/matlab/ref/addpath.html
  • Rename one of the 'MMG.m' files and then restart MATLAB.
If the issue persists, you can use the MATLAB debugger to identify which function is being called when you run the application.
For more information regarding how to debug MATLAB code, refer to this documentation: https://www.mathworks.com/help/matlab/matlab_prog/debugging-process-and-features.html

Categories

Find more on Variables in Help Center and File Exchange

Products


Release

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!