Use the mustBeFolder function to ensure that a folder path passed to a function is a valid folder and avoid using conditional statements to test for a valid folder in the function body.
The runInFolder function ensures that the specified folder is valid before changing to that folder to run a function.
function r = runInFolder(path)
arguments
path {mustBeFolder}end
orgFolder = cd(path);
r = myFunct;
cd(orgFolder)
end
Passing an invalid folder name as the input results in an error.
r = runInFolder("myFunct.m");
Error using runInFolder
Invalid argument at position 1. The following folders do not exist: 'myFunct.m'.