Switching between functions that have the same name

5 visualizaciones (últimos 30 días)
Mehdi Moussaid
Mehdi Moussaid el 9 de Abr. de 2021
Comentada: Mehdi Moussaid el 10 de Abr. de 2021
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 !

Respuesta aceptada

Walter Roberson
Walter Roberson el 9 de Abr. de 2021
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 comentarios
Walter Roberson
Walter Roberson el 9 de Abr. de 2021
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 el 10 de Abr. de 2021
Ok, thanks for the precision. +1

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Environment and Settings en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by