user915783
user915783

Reputation: 699

How to get path in matlab relative to specified path that is stored in variable

I have a path of currently executing script stored as:

currentDir = mfilename('fullpath');

I need to get path , 2 levels up from this path. I know that

'..\..\'

would do the job if executed within the script. But, i need a solution that can do similar stuff using the variable currentDir.

Thanks
sedy

Upvotes: 0

Views: 41

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112659

Use find to locate the third occurence of \ (or filesep for more generality) starting from the end of the string, and cut there:

currentDir = 'C:\example\path\to\file\filename.m'; %// example full filename
ind = find(currentDir==filesep,3,'last');
result = currentDir(1:ind(1)-1);

In this example,

result =
    C:\example\path

Upvotes: 2

Related Questions