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)
![Admin](/assets/logo_square_200-5d0d61d6853298bd2a4fe063103715b4daf2819fc21225efa21dfb93e61952ea.png)
Author by
Admin
Updated on June 04, 2022Comments
-
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 over 7 yearsI think it is cd(fileparts(mfilename('fullpath')));
-
mobeets over 7 yearsUnlike 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 over 5 yearsOr
cd(fileparts(which(mfilename)))
-- but onlycd(fileparts(mfilename))
does not work.