JB_User
JB_User

Reputation: 3267

Error using dir Function is not defined for 'string' inputs

I'm writing my first Matlab script, and I get an error trying to use dir(). This is the script:

strLocation = "C:\Users\myname\Documents\MATLAB";
listing = dir(strLocation)

The error is:

Error using dir
Function is not defined for 'string' inputs.

What am I doing wrong?

Upvotes: 2

Views: 1287

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

It should first be noted that a char vector and a string are different things in Matlab. The string data type was introduced recently (in R2016b, I think). Previous versions do not support the string type, only char vectors.

Since the string data type was introduced, many built-in functions that used to accept char vector input can now accept string input as well. But this is being gradually incorporated into functions, apparently. So, even if your Matlab version supports the string data type, you may find some functions that still can only take a char vector as input. This seems to the case for dir in your version. In R2018b dir supports both types of input, according to the documentation.

So, you need to define the input to dir as a char vector. For this you use ' instead of ":

strLocation = 'C:\Users\myname\Documents\MATLAB';
listing = dir(strLocation)

Or, if you must have a string, convert it to a char vector before passing it to dir:

strLocation = "C:\Users\myname\Documents\MATLAB";
listing = dir(char(strLocation))

Upvotes: 8

Jakob L
Jakob L

Reputation: 196

Since MATLAB R2017a double quotation marks denotes strings and single quotation marks denotes character vectors.

The dir function requires a char vector so you should call it with single quotation marks,

strLocation = 'C:\Users\myname\Documents\MATLAB';
listing = dir(strLocation)

Upvotes: 2

Related Questions