How to get the name of the parent folder of a file specified by its full path?

Karnivaurus picture Karnivaurus · Mar 19, 2014 · Viewed 22.6k times · Source

In Matlab, I have a string containing a path to a file:

path = 'C:/Data/Matlab/Dir/file.m'

I want now want to extract the 'Dir' part of the string. One way to do this is:

[first, second, third, fourth, fifth] = strtok(path, '/')

And then take the fourth element, and finally remove the first character from it (the /).

I'm just wondering if there is a more elegant solution? It seems a little cumbersome to have to explicitly store all the first ... fifth elements and then manually remove the /.

Thanks.

Answer

bouhmidou picture bouhmidou · Sep 27, 2017

you can try the fileparts function as follow:

[ParentFolderPath] = fileparts('C:/Data/Matlab/Dir/file.m');
[~, ParentFolderName] = fileparts(ParentFolderPath) ;
ParentFolderName = 'Dir'