how to open a file from the previous folder

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?

 Respuesta aceptada

Geoff Hayes
Geoff Hayes el 12 de Jun. de 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.

7 comentarios

But i'm located on B, so i have to go back to A and then up to C, this code works if y was firstly located on A... no¿
Geoff Hayes
Geoff Hayes el 13 de Jun. de 2020
Based on your picture, I assumed that both B and C were folders within A. Is my assumption false? Or are B and C not sub-folders within A?
That’s true, B and C are sub-folders within A
Geoff Hayes
Geoff Hayes el 13 de Jun. de 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.
Wow sorry, the code you give me bellow works, thank you so much!!!!
Geoff Hayes
Geoff Hayes el 13 de Jun. de 2020
No problem! :)
" had thought about using fullfile to build the pathToFolderC but (on my version of MATLAB),the '..' was not being included in the path."
Odd. It works here:
folderCName = 'someFolderName';
pathToFolderC = fullfile(pwd,'..',folderCName)
pathToFolderC = '/users/mss.system.g8rKA4/../someFolderName'

Iniciar sesión para comentar.

Más respuestas (2)

Amine BEROUAKEN
Amine BEROUAKEN el 31 de En. de 2024
Hello, you can use this code
imagePath = fileparts(pwd) + "\FloderCName\imageName.png";
Stephen23
Stephen23 el 31 de En. de 2024
Note that there is absolutely no need to call PWD. Simply use '.' to refer to the current directory:
relativePathToC = './../C';

Categorías

Más información sobre Convert Image Type en Centro de ayuda y File Exchange.

Productos

Versión

R2020a

Etiquetas

Preguntada:

el 12 de Jun. de 2020

Comentada:

el 31 de En. de 2024

Community Treasure Hunt

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

Start Hunting!

Translated by