MATLAB Answers

how to open a file from the previous folder

21 views (last 30 days)
Hello, I have a folder hierarchy like the one in the image, I'm running a script from folder B and what I want is to open an image that is in folder C, but the path to it can change, that is, I want the code to be the same regardless of whether the folder A is on the desktop or in my documents for example.
Does anyone know how to program that?


Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 12 Jun 2020
Alajendro - you should be able to use pwd to determine the current folder, and then "navigate" up one directory to A and then down one to C. I'm assuming that you know the name of folder C.
currentPath = pwd;
folderCName = 'someFolderName';
pathToFolderC = [pwd filesep '..' filesep folderCName filesep];
I had thought about using fullfile to build the pathToFolderC but (on my version of MATLAB),the '..' was not being included in the path.


Show 3 older comments
Geoff Hayes
Geoff Hayes on 13 Jun 2020
So the pwd will give you the current path which should be B. Say something like "/users/geoffh/folderB". We append the .. to get "/users/geoffh/folderB/.." which means that we now have the path to folder A. We then append the folder C name to get "/users/geoffh/folderB/../folderC" which means that we now have the path to folder C.
Alejandro Fernández
Alejandro Fernández on 13 Jun 2020
Wow sorry, the code you give me bellow works, thank you so much!!!!

Sign in to comment.

More Answers (0)




Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!