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?
Open the Current Folder Browser MATLAB Toolstrip: On the Home tab, in the Environment section, click Layout. Then, in the Show section, select Current Folder.
Change Startup FolderOn the Home tab, in the Environment section, click Preferences. Select MATLAB > General. Choose an option for the Initial working folder preference. Alternatively on Windows platforms, specify the initial working folder in the MATLAB shortcut icon.
I found the solution (was looking in wrong direction before).
tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With