Hello,
I created a function which requires several user inputs. Some input combinations can cause an error. During the execution of the function, some directory changes happen. After the function has finished, it returns in the original folder but in case an error occurs, it will be stuck in of the other directories. How can I automatically switch back to the Folder where the .m file is located?
I read about the try and catch function but I'm unsure if they work for what I want and how I would use them. If they are suitable for my problem, can you give an example in pseudocode how to use it?
Thank you.

댓글 수: 2

Stephen23
Stephen23 2016년 2월 24일
편집: Stephen23 2016년 2월 24일
The best solution is do not change directories. There is rarely a reason for doing this. If you only need to access files in those other folders then just create absolute or relative paths and use these. This is much faster and much more robust.
Summary: Switching directories is slow, a pain to debug, and a pain when it gets messed up. It is much simpler and faster to use absolute or relative filepaths. All MATLAB functions accept them, so there is no reason why you should not use them.
@Stephen: Please post this as an answer, because it is the best solution. The current folder might be changed unexpectedly in a timer or GUI callback during a function is running. So using absolute paths in every case is the only reliable method.

댓글을 달려면 로그인하십시오.

 채택된 답변

Stephen23
Stephen23 2016년 2월 24일

2 개 추천

The best solution is do not change directories. There is rarely a reason for doing this. If you only need to access files in those other folders then just create absolute or relative paths and use these. This is much faster and much more robust.
Summary: Switching directories is slow, a pain to debug, and a pain when it gets messed up. It is much simpler and faster to use absolute or relative filepaths. All MATLAB functions accept them, so there is no reason why you should not use them.

추가 답변 (1개)

Steven Lord
Steven Lord 2016년 2월 24일
You can create an onCleanup object that will CD back to the original directory when it leaves scope. The whole purpose of the onCleanup object is to die and with its last breath do something.
function onCleanupExample
P = pwd;
goback = onCleanup(@() cd(P));
fprintf('Before CD, inside %s\n', P)
cd(tempdir)
fprintf('After CD, inside %s\n', pwd)
error('Throw an error');
Assuming you weren't in your TEMPDIR before, you should see that you are back in the directory printed in the "Before CD" line. You should also see the error message.
[Just as an aside, If you were doing this in the context of a test class in the unit testing framework, I would recommend using the addTeardown method instead.]

카테고리

도움말 센터File Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

질문:

2016년 2월 24일

댓글:

2016년 2월 25일

Community Treasure Hunt

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

Start Hunting!

Translated by