If you do not want to care about the number of elements in your path, and you do not want to use strsplit , which is not available in older versions of Matlab, you can also use this one liner:
directory = getfield( fliplr(regexp(fileparts(path),'/','split')), {1} ) %% or: % alldir = regexp(fileparts(path),'/','split') % directory = alldir(end)
which will always return the parent folder of the specified file.
You should also consider using filesep instead of '/' for better compatibility with various systems.
source share