user915783
user915783

Reputation: 699

How to default to location of the script on error in matlab

I have a Matlab(R2017b) script that is at path:

path1: C:\ComputeCode\Scr1.m

and a script like:

path2: C:\ComputeCode\OtherFiles\Scr2.m

Scr1.m has a code which does bunch of stuff like below:

   %..... Scri.m.....%
   ..open files and do some processing...
   cd(path2)
   .. execute Scri2.m and do some processing ...

The issue is that if there is an error in Scr2.m, the control does not come back to path1, but stays in path2.
How do I add some code at start of Scr1.m, so that whenever any exception/error pccurs in matlab, it always default to path1 for execution.

Upvotes: 2

Views: 51

Answers (2)

sco1
sco1

Reputation: 12214

The proper way to accomplish this would be to utilize absolute file paths rather than relative ones so you don't have to worry about having to cd into a directory for proper functionality.

Other methods include:

onCleanup, which executes code when the output object is destroyed. Note that this will require you to make Scr1 a function in order to work with minimal additional effort.

For example, we have SOcode.m:

function SOcode
home = pwd;  % Store base directory
cleanupObj = onCleanup(@()cd(home));

cd(fullfile('./testfldr'))  % Use fullfile for platform independence
asdf
end

And ./asdf.m, which contains an error:

disp(a)

Upon execution of SOcode, you'll receive an error:

>> SOcode
Undefined function or variable 'a'.

Error in asdf (line 1)
disp(a)

Error in SOcode (line 6)
asdf

But be returned back to the base directory.


Alternatively, you can use a try/catch to catch the exception and return to the home directory before rethrowing the error. This approach does not require Scr1 to be a function.

For example, we now have SOcode.m:

home = pwd;

cd(fullfile('./testfldr'))

try
    asdf
catch e
    cd(home)
    rethrow(e)
end

With the same ./asdf.m, for the same result.

Upvotes: 4

bla
bla

Reputation: 26069

Use try and catch

%..... Scri.m.....%  ..open files and do some processing...
try
   cd(path2)

.. execute Scri2.m and do some processing ...
catch
     cd(path1)
     break
end

or something similar...

Upvotes: 3

Related Questions