Search code examples
matlabstring-parsing

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


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.


Solution

  • Try:

    parts = strsplit(path, '/');
    DirPart = parts{end-1};