Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 534
Vitamin-B Avatar asked Jun 14 '14 20:06

Vitamin-B


People also ask

How do I get the current directory in MATLAB?

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.

How do I change the default directory in MATLAB?

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.


2 Answers

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

tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
like image 166
Vitamin-B Avatar answered Oct 18 '22 01:10

Vitamin-B


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)

like image 3
Daniel Avatar answered Oct 18 '22 00:10

Daniel