Switching between functions that have the same name

Hi,
I have 30 folders, each one containing a different version of a class named 'myClass.m'.
I would like to call these different versions sequentially from a main script.
In the script, I loop 30 times, every time changing the path like this :
for i=1:30
restoredefaultpath ;
addpath(versionPath);
% work with this version of the class %
end
But this seems not to work. Every time I change the path, Matlab seems to "remember" the previous version of the class.
Is there any way to make this in a cleaner way ?
Thank you in advance !

 采纳的回答

You do not need to restoredefaultpath but you do need to remove the previous folder
You do, however, need to clear the class.
p = path;
cleanME = onCleanup(@() path(p));
for i = 1:30
addpath(versionPath{i});
clear myClass
% work with this version of the class
path(p)
end

3 个评论

Thanks ! Your solution seems to work good so far.
I'm not sure however what the "onCleanup" function means and when it is called ?
cleanME = onCleanup(@() path(p));
when the variable cleanME is deleted, then the anonymous function will be executed, which would cause the path to be returned to whatever is in p .
This is a safeguard in case something goes wrong; if your code bombs before the path(p) call inside the loop, then your path will automatically be fixed back up if you "clearvars" or "clear all". If this loop is inside a function and the function returns (perhaps because of an error in one of the classes) then the local variable cleanME would be automatically removed, and that would trigger cleaning up the path.
When you have code that is making temporary changes to the path, or code that is using cd(), then it is a good programming practice to configure an onCleanup() to restore to known state in case of problems.
Ok, thanks for the precision. +1

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品

版本

R2019b

标签

Community Treasure Hunt

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

Start Hunting!

Translated by