trying to use the dir / cd(dir) function, "error using cd. unable to change current folder to...(name is nonexistent or not a folder)" message appears

Hi
I am working on an assignment and the first question asks to define the directory. The function I am having trouble with is dir and cd(dir). I am using the live editor function on the online version of Matlab. After following the instructions provided to me from my prof, I end up with this message ""error using cd. unable to change current folder to '/MATLAB Drive/C: \Users\X\Documents\school\Labdata.xlsx'. (name is nonexistent or not a folder). X is just my name. My code is this:
dir = 'C: \Users\X\Documents\school\Labdata.xlsx' ;
cd(dir)
Can someone please explain why I am having this issue and how I can resolve it? Thank you in advance!

1 Comment

dir = 'C: \Users\X\Documents\school\Labdata.xlsx' ;
% ^ invalid path name
% ^^^^^^^^^^^^ cannot CD to a file
%^^ variable name is best avoided

Sign in to comment.

 Accepted Answer

dir = 'C: \Users\X\Documents\school\Labdata.xlsx' ;
Don't use dir as a variable name--it's a builtin function. Use something more like
infile = 'C: \Users\X\Documents\school\Labdata.xlsx';
Isn't the root cause of your problem but will wreak havoc later if you then try to use dir()...
The reason cd doesn't work, though, is that that is a fully-qualified file name, pointing to a file, NOT a directory. Hence, you can't cd to a file.
indir = 'C: \Users\X\Documents\school';
cd(indir)
would be what you're looking for there, but it is better practice to not change directories willy-nilly, but to use the fully qualified file name to reference the file from your working dirctory...
indir = 'C: \Users\X\Documents\school';
infile = 'Labdata.xlsx';
fqn=fullfile(indir,infile);
...
Now you use the fqn variable to address the file; fullfile builds it with correct punctuation and you don't need to actually change the working directory at all.

More Answers (0)

Categories

Products

Release

R2023a

Asked:

on 15 Jul 2023

Commented:

on 16 Jul 2023

Community Treasure Hunt

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

Start Hunting!