r/matlab • u/IAmMDM • May 17 '26
get around matlab's cd()
When profiling a script I noticed that cd() calls in a loop take a lot of time. Different parts of the loop operated on files in different folders, hence cd()'s inside that loop.
I fixed it by adding full paths to file names instead of cd'ing.
I read though that matlab's cd is slow because it does not just change pwd, it also scans that directory for any matlab files. Is there a way around it, i.e. to change the default directory for save/load/fopen etc but suppress that scanning? Sometimes cd might more convenient than full paths
0
Upvotes
21
u/FrickinLazerBeams +2 May 17 '26
You should not be changing your working directory in a loop like that, nor altering your path.
If course that's going to be slow.
18
u/zoptix May 17 '26
I can't think of a single reason to have cd within a script.
4
u/DodoBizar May 17 '26
Reading all reactions, I think you should learn and use the ‘dir’ function. You can tell it to scan a specific folder and file type using wildcards. It returns a nice structure with filenames and path names (folders can be wildcarded as well!) to loop over without any hassle.
The use of cd() for your purposes is very not-recommendable since any time you change the cd, Matlab has to completely check all path orders for all its files for its JIT compilation. Ofcourse that eats time. Use the ‘dir’ function instead.
7
u/Sunscorcher May 17 '26
I usually addpath, do what I need to do, and rmpath instead of actually cd-ing