Search code examples
matlabdirectorycd

How to define a custom directory so that I can cd directory in Matlab


Suppose I have a directory

cur = 'C:\Windows\debug';

Then I can run cd(cur) now. But I'm not used to using the function format. I hope I can use cd cur to change the current folder directly. Is this possible in MATLAB?

Edit: Because I'm getting the following error:

>> cur = 'C:\Windows\debug';
>> cd cur
Error using cd
Cannot CD to cur (Name is nonexistant or not a directory).

Solution

  • Here is the documentation for command syntax, and a documentation article with more examples on command vs function syntax.

    From the docs,

    When calling a function using command syntax, MATLAB passes the arguments as character vectors.

    So no, you cannot pass a variable name like cur, because cur will get treated as a character vector and you will be doing the same as cd('cur').

    You can do either

    cd(cur)
    % or
    cd 'C:\Windows\debug'
    % or (as long as no whitespace in directory path)
    cd C:\Windows\debug
    

    If you don't like learning the syntax, the workaround is to choose another language... Using brackets is standard practise in MATLAB, since you also cannot get output values from a function when using command syntax.

    Also from the scripts and functions documentation you can see the message

    Caution: While the unquoted command syntax is convenient, in some cases it can be used incorrectly without causing MATLAB to generate an error.

    So this method is discouraged when using MATLAB.