Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 414
Karnivaurus Avatar asked Mar 19 '14 14:03

Karnivaurus


1 Answers

you can try the fileparts function as follow:

[ParentFolderPath] = fileparts('C:/Data/Matlab/Dir/file.m');
[~, ParentFolderName] = fileparts(ParentFolderPath) ;
ParentFolderName = 'Dir'
like image 77
bouhmidou Avatar answered Sep 20 '22 15:09

bouhmidou