Changing working directory in matlab to current script dir with running blocks

10,709

Solution 1

I found the solution (was looking in wrong direction before).

tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));

Solution 2

You can use mfilename to get the current script name, cd(fileparts(mfilename)) should change to the correct directory.

If you frequently have to run scripts which need to be run in their script directory, you can use this function:

function varargout=run_in_dir(fun,varargin)
location=which(func2str(fun));
assert(exist(location,'file')~=0,'fun does not seem to be a m. file');
old_dir=pwd;
cd(fileparts(location));
try
if ~isempty(varargin)
    [varargout{1:nargout}]=fun(varargin{:});
else
    [varargout{1:nargout}]=fun();
end
catch ME
    cd(old_dir)
    rethrow(ME)
end
cd(old_dir)
end

To run sin(3) in the directory where sin is defined, use run_in_dir(@sin,3)

Share:
10,709
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin about 2 years

    Is there a way to change the current working directory to current script directory with running code just inside one block of script? Script folder is not added to path.

    Redefined: Is there a way to to change the current working directory to script that's currently active in editor?

  • Mohamed Hamed
    Mohamed Hamed over 7 years
    I think it is cd(fileparts(mfilename('fullpath')));
  • mobeets
    mobeets over 7 years
    Unlike the solutions using mfilename, this one actually works when you're not running the command inside the file itself (or when executing a cell).
  • Robert Seifert
    Robert Seifert over 5 years
    Or cd(fileparts(which(mfilename))) -- but only cd(fileparts(mfilename)) does not work.