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 !

 採用された回答

Walter Roberson
Walter Roberson 2021 年 4 月 9 日

0 投票

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 件のコメント

Mehdi Moussaid
Mehdi Moussaid 2021 年 4 月 9 日
Thanks ! Your solution seems to work good so far.
I'm not sure however what the "onCleanup" function means and when it is called ?
Walter Roberson
Walter Roberson 2021 年 4 月 9 日
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.
Mehdi Moussaid
Mehdi Moussaid 2021 年 4 月 10 日
Ok, thanks for the precision. +1

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops 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