Access data files from subfolder of current script directory - matlab

I have been working on MATLAB scripts.
Basically, I have a lot of functions and data files (collectively known as kernels):
I want to organize it a little bit.
The idea is
to create a subfolder named functions and save all functions in it.
Another kernels and save all data kernel files in it.
Later by adding these paths at runtime, all the scripts should be able to access these functions and kernels without giving the full path to them, i.e. The script should search it in the subfodlers too.
Applying addpath(genpath(pwd)); worked for functions but it couldn't access kernel files
e.g. What if I want to access file named naif0010.tls inside subfolder kernels.
It didn't work. Any suggestions.
Example:
% Add the current script directory and subfolders to search path
addpath(genpath(pwd));
% Load NASA Spice (mice) to the script here
% add MICE reference path to MATLAB
addpath('C:\Program Files\MATLAB\R2012b\extern\mice\src\mice');
addpath('C:\Program Files\MATLAB\R2012b\extern\mice\lib');
% Load leap second kernel
% If the leapsecond kernel is placed in script directory
% This file is present in pwd/kernel/naif0010.tls
cspice_furnsh('naif0010.tls');

There are a couple of things to keep in mind. First, your current working directory (pwd) is in the Matlab path by default, so you don't usually need to explicitly call addpath in order to use scripts, functions, or data files there.
Also, in many cases you can access files by providing a relative path rather than an absolute path. In your case, this would look like
cspice_furnsh('kernels/naif0010.tls')

I solved it with some work around which I know is not the correct answer but for now I can go ahead....
addpath(genpath(pwd));
% Basically just forming full path of the data file
leapSecondsFile = fullfile(pwd,'kernels','naif0010.tls');
cspice_furnsh(leapSecondsFile);
Still waiting for correct answer or suggestions :-)
Update:
Thanks nispio's comment above, The correct way is :
% Load current directory and subfolders
addpath(genpath(pwd)); % This is not necessary
cspice_furnsh('kernels\naif0010.tls');

Related

Open multiple subfolders within a loop

I have a folder named "Photos" that is a subfolder of the current directory. Inside that folder, there are four subfolders with names "Order1", "Order2",
"Order3", "Order4". I am trying to open these subfolders using a loop.
The following code is not working.
for i=1:4
current_path=pwd;
cd(current_path');
cd('Photos\Order%d',i);
end
There are a lot issues going on here at the same time.
The primary issue is that you are changing directories each time through the loop but you're also getting the value of the current directory (pwd) each time. The directory doesn't automatically reset to where you were when it goes back to the top of the loop. I think you expect current_path to be the folder you started in and be the same for all iterations.
You need to use sprintf or something similar to create your "OrderN" folder names. cd doesn't know what to do with the format specifier you're trying to use.
You should always use fullfile when concatenating file paths. Period.
You should use absolute paths when possible to remove the dependence upon the current directory.
Do you really need to change the working directory? If you're trying to load files within these folders, please consider using absolute file paths to the files themselves rather than changing folders.
If you are going to do this this way, please be sure to reset the path back to where it was at the end of the loop. There is nothing worse than running code and ending up in a directory that is different than where you were when you called it.
To actually make your code work, we could do something like this. But given all of my points above (specifically, 4-5), I would strongly consider a different approach.
startpath = pwd;
for k = 1:4
folder = fullfile(startpath, 'Photos', sprintf('Order%d', k));
cd(folder)
end
% Set the current directory to what it was before we started
cd(startpath)

Multiple pathdef files in Matlab?

Suppose two different Matlab users share a computer and they each want to be able to save and load their own Matlab paths. (Or, a single user wants to use different paths at different times.) What's the easiest way to handle this?
Should there be multiple pathdef files? Alternatively, should they each have a script that calls restoredefaultpath and then uses addpath to add new paths?
You can use the startup.m file for that.
When starting up, Matlab executes the file matlabrc.m, which is the master startup file, and is common for all users. Among other things, this file
Sets the first entry of the path as the user-folder of the current user, that is, the user that started Matlab. (This is done by calling pathdef, which in turn calls userpath); and then
Looks for a startup.m file in the path, end executes if it exists.
Therefore you can place a user-specific startup.m file in each user's folder, and Matlab will run the appropriate file depending on which user started Matlab. In that file you can set the path on a per-user basis, and do other user-related stuff.

setting a default matlab path at startup

My team is trying to standardise our Matlab paths so that everyone has the same.
I have a list of the default matlab path that we should all have.
So we would like to have a script that runs when matlab opens to make sure that our paths are set to the default matlab path. So if a path has been added to our default list it will be added in the correct place.
Is this possible in Matlab?
I read about startup but that seems to do with set your working directory which is different to what I am trying to do.
You can change which directory MATLAB starts in using the userpath function so that whenever you start up MATLAB, the path will automatically redirect here.
This may be useful if you have MATLAB running on a network per se, and multiple instances can start in the same network directory.
See more from MathWorks here: http://www.mathworks.com/help/matlab/matlab_env/matlab-startup-folder.html
However, if you want to standardize everything so that everyone has access to the same path, you can use startup to add directories / folders to MATLAB's path, but if you want to complete the package, use userpath to get MATLAB to start at a specified directory.
Your startup.m file may look something like this:
addpath('/folder/to/add/one');
addpath('/folder/to/add/two');
addpath('/folder/to/add/three');
addpath('/folder/to/add/four');
Then set your userpath with the function to complete everything:
userpath('/folder/to/start');
addpath('/folder/to/start');
Also make sure you add this new folder to your startup.m file too.
Include a path or addpath line in file startup.m. For example, to add folder aaa\bbb to the path the line would be
addpath('aaa\bbb')
Note that each user may have a different startup.m file. You may need to create it, if it doesn't already exist.

matlab creating paths to stop copying code

I have created a few general function in MATLAB that I intend to use for a few separate projects. However I do not want to copy the function into each separate project function.
I have created a folder called Misc_Function when I have placed these general functions. I know I can reference this functions explicitly by using the path and function name when trying to call the functions.
I believe you can add a path (in my case 'H:\MyTeam\Matlab\Misc_Function') when MATLAB loads up is that correct and if so how do you do this?
Assuming the above can be done I'm interested to know how MATLAB finds the correct function. In my understanding (guess work) MATLAB has a list of paths that it check trying to find a function with the name specified - is that correct? If so what happens when there are functions with the same name?
MATLAB indeed has its own search path which is a collection of folders that MATLAB will search when you reference a function or class (and a few other things). To see the search path, type path at the MATLAB prompt. From the documentation:
The order of folders on the search path is important. When files with the same name appear in multiple folders on the search path, MATLAB uses the one found in the folder nearest to the top of the search path.
If you have a set of utility functions that you want to make available to your projects, add the folder to the top of the search path with the addpath function, like so
addpath('H:\MyTeam\Matlab\Misc_Function');
You have to do this everytime you start MATLAB. Alternatively, and more conveniently, save the current search path with the savepath command or add the above commands to your startup.m file.
You can check the actual paths where Matlab searches for functions using
path
You will notice, that the most top path (on start up) is a path in your home folder. For Linux this is e.g. /home/$USER/Documents/MATLAB. For Windows it is somewhere in the the c:\Users\%USER%\Documents\Matlab (I think). Placing a file startup.m in this folder allows to add additional paths using
addpath('H:\MyTeam\Matlab\Misc_Function');
or
addpath(genpath('H:\MyTeam\Matlab\Misc_Function'));
on start up of Matlab. The latter (genpath) allows to also add all subdirectories. Simply write a file startup.m and add one of above lines there.
I believe 'addpath' will add the folder to MATLAB path only for the current MATLAB session. To save the updated path for other sessions, you need to execute 'savepath' command.
As mentioned in the previous comments, adding the folder in startup.m is a good idea since it will be added to the path on MATLAB startup.
To answer your question about how MATLAB finds the correct function, MATLAB maintains a list of directories in its path in a file called pathdef.m. Any changes to the path will be written to this file (when you execute 'savepath'). The path variable is initialized with the contents of this file.

automatically add path in a MATLAB script

I have several MATLAB scripts to share with my colleagues. I have put these scripts under a specified directory, e.g., /home/sharefiles
Under the MATLAB command prompt, the users can use these scripts by typing
addpath /home/sharefiles
Is there a way to automatically add this path in my matlab script, and save users the efforts of invoking addpath /home/sharefiles each time.
Sure, just add the addpath to your script.
addpath('/home/sharefiles')
If you want to recursively add subdirectories, use the genpath function:
addpath(genpath('/home/sharefiles')
Adding files to the path or one of the slower operations in Matlab, so you probably don't want to put the addpath call in the inner loop of an operation. You can also test to see if you need to add the path first.
if ~exist('some_file_from_your_tools.m','file')
addpath('/home/sharefiles')
end
Or, more directly
if isempty(strfind(path,'/home/sharefiles;'))
addpath('/home/sharefiles')
end
You could add the code posted by Pursuit to your startup.m file so that MATLAB adds it to the path automaticlly upon startup. Or, take a look at the savepath function. Lastly,
So when you Use the GUI to set path, the paths get added in the default start directory of Matlab in the pathdef.m file present there. Hence if you are running your code from any other directory either you would have to copy over this file or create a script in the startup folder. Hope this helps!!