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?
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With