You can change the current folder in MATLAB using the cd
command.
In MATLAB, the current folder is the directory where MATLAB looks for files by default when you run scripts or functions, and where it saves new files unless a full path is specified. Changing the current folder is a fundamental operation for managing your MATLAB projects and files.
Using the cd
Command
The primary way to change the current folder in MATLAB is with the cd
command, which stands for "change directory".
-
To change the current folder to a specific directory, use the command followed by the path to the desired folder:
cd 'path/to/your/folder'
Remember to use single quotes around the path, especially if it contains spaces. On Windows, you can use either backslashes (
\
) or forward slashes (/
) in the path, though using\
often requires doubling them or using forward slashes to avoid issues with escape sequences. For example,cd 'C:/Program Files'
orcd 'C:\\Program Files'
. -
To display the current folder, simply type
cd
without any arguments:cd
This command will print the full path of the directory you are currently in within MATLAB.
Example: Changing and Restoring the Folder
Based on the provided reference, you might need to temporarily change the folder and then return to your original location. Here's how you can do that using the cd
command:
- Save the original folder path: Use
cd
(which returns the current path when assigned to a variable) orpwd
(print working directory) to store the path of your current directory in a variable. - Change to the new folder: Use
cd
with the path to the new directory. - Display the new current folder: Use
cd
without arguments to confirm the change. - Change back to the original folder: Use
cd
with the saved path stored in the variable. - Display the restored current folder: Use
cd
without arguments again to confirm you are back.
Here is the sequence of commands illustrating this process:
% 1. Save the current folder path
originalFolder = cd;
% 2. Change the current folder to C:\Program Files
cd 'C:\Program Files'
% 3. Use the cd command to display the new current folder
disp('Current folder after changing:');
cd
% 4. Change the current folder back to the original folder, using the stored path
cd(originalFolder);
% 5. Use the cd command to display the new current folder (restored)
disp('Current folder after restoring:');
cd
This method is useful when you need to access files in a different directory temporarily without losing track of your starting point.
For more details on the cd
command and other file navigation functions, you can refer to the official MATLAB documentation for cd.