Reading data files within a subfolder of the search path?

I would like to be able to have all my functions in the ML searchpath, but have all of my data in subfolders. Then I would enter that subfolder name into the function I am calling and it would be able to use the functions within the primary folder, but take data from the subfolders. Is there any way to accomplish this? Or do I just need to have all functions and data to be analyzed in the primary search path?

Answers (2)

There is no requirement for data to be on the Matlab path. How you access the data is up to you, but if it is not on the Matlab path you have to give a full path name when accessing it.
This path name can be constructed from components depending on what knowledge you have at the point you need to construct it though.
e.g.
doc mfilename
can be used if you want to create a path relative to the currently executing m-file.

4 Comments

Thanks, Adam. However, my executing m-file (in which I want to put the code to look into subfolders) is on the same level as the folders I want to look into. I guess what I'm not sure of is the actual syntax.
So my script is running and loading files (at this point all within the same folder) and I want it to be able to look into a folder that is on the same searchpath level for data.
Ex: Current script is
C:/MATLABLocomotionPD/LocomotionPD.m
and the data would be in
C:/MATLABLocomotionPD/datafilefolder/dataIwantToImport
I just need to look into these folders (and maybe go deeper in the future). Since there might be many places I want to look into folders in the future, I am looking for an efficient syntax to accomplish this. Thanks!
Inside LocomotionPD.m you can use a relative path:
strPath = 'datafilefolder';
strName = 'dataIwantToImport.txt';
strFull = fullfile(strPath,strName);
fid = fopen(strFull,'rt');
...etc
you can use a fullpath (ie. a filename complete with the path as well) with any MATLAB functions that accesses files. You can locate/identify those directories and files using dir or exist or the like.
Thanks Stephen! That's what I was looking for.
Appreciate everyone else's help as well!
You'll still need to use genpath() (like I showed you in my Answer) to get the list of subfolders like you said you want. You can use dir() and then search for "." but that is far less convenient. But I don't think you want to be hard coding in all the subfolders.

Sign in to comment.

You can use genpath() to generate all subfolders of C:/MATLABLocomotionPD/datafilefolder in a cell array:
caPathList = genpath('C:/MATLABLocomotionPD/datafilefolder');
From there you can use dir() and fullfile() to specify the complete path of any file in any of those folders. See attached m-file for a demo.

Categories

Asked:

on 22 Mar 2016

Commented:

on 18 Oct 2017

Community Treasure Hunt

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

Start Hunting!