Why does MATLAB not allow me to pass an argument, which contains a space, to certain functions?

23 views (last 30 days)
I have a string with a space in it, such as a path to a specific file:
C:\my work\result.jpg
When I use this file path as an argument to PRINT, I receive an error:
print -djpeg C:\my work\result.jpg
??? Error using ==> print
Error using ==> d:/applications/matlab6p5/toolbox/matlab/graphics/private/inputcheck
Multiple inputs that look like filenames: 'C:\my' and 'work\result.jpg'
Similarly, when I use the directory path as an argument to CD, I receive an error:
cd C:\my work
??? Error using ==> cd
Too many input arguments.
This error can also happen with, but is not limited to, the following commands:
EXIST, WHICH, LS, DIR, WHAT, SAVE, LOAD, etc.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 27 Jun 2009
When using the command form of a function, if you pass a string with a space in it, it is expected that you will receive an error. The reason for this is because of the behavior of MATLAB's command/function duality, as described in the documentation, obtained by clicking on the following link:
<http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f7-58170.html#f7-58289>
Here is a summary of what command/function duality is:
The following code illustrates an example of calling a function using command syntax:
cd C:\work
Notice that in this code, there are no parentheses used to pass the argument in. This is because all inputs following the function call are automatically interpreted as strings. When you use parentheses to pass in arguments, it is called using the function form, and it requires you to explicitly pass the argument as a string. Therefore, the following function form is identical to the previous command form:
cd('C:\work')
If you have a path with a space in it, and you want to use CD on it (as in the following code) this will not work because it will be interpreted as passing two arguments to CD:
% Command form that implies two input arguments, and that will error out:
cd C:\my work
% The corresponding function form would look like this, and will also error out
% because it has two input arguments:
cd('C:\my', 'work')
This results in an error, since CD does not take more than one input argument.
Here are several examples for working around this problem when using the CD command. Of course, the same ideas can be applied to any MATLAB commands that have command/function duality:
% Using single quotes to hard code the string:
cd 'C:\my work'
% Using functional form:
cd('C:\my work')
% Using a character array variable in addition to functional form:
p = 'C:\my work';
cd(p)

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!