-2

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).
Wolfie
  • 27,562
  • 7
  • 28
  • 55
yode
  • 483
  • 7
  • 16
  • To `cd` to a directory contained in a variable, as you are trying, you must use the functional form. In your example MATLAB is looking for a directory called `cur`. – Phil Goddard Jul 18 '17 at 15:18
  • @PhilGoddard Of course I know,But I I'm want to do this still.Is there any workaround? – yode Jul 18 '17 at 15:22
  • 2
    To quote the documentation for `Command vs. Function Syntax`: `When a function input is a variable, you must use function syntax to pass the value to the function. Command syntax always passes inputs as literal text and cannot pass variable values`. I don't believe there's a workaround. – Phil Goddard Jul 18 '17 at 15:23
  • @PhilGoddard,Wolfie Thanks.Just because I'm a *Linux* user,it hard to used to use cd(dir) to change the directory.I thinks must exist some method can make the variable release its value in the command line directly. – yode Jul 18 '17 at 15:27

1 Answers1

2

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.

Wolfie
  • 27,562
  • 7
  • 28
  • 55
  • I'm highly doubt [that command](http://i.stack.imgur.com/3Nq2D.png) can work still.And the `cd(cur)` work normally in here. – yode Jul 18 '17 at 15:20
  • Sorry,I have known the sytax actually,I just hard to used to use cd like that style. – yode Jul 18 '17 at 15:28
  • Unfortunately you will have to get used to it, there isn't a workaround. I hope this answer provided useful information, if so consider marking it as accepted. – Wolfie Jul 18 '17 at 15:31
  • Thanks anyway,if there are no solution still after 36h,I will accept it. – yode Jul 18 '17 at 15:38