relative path for a MATLAB program called via the search path - matlab

I wrote a MATLAB program with a GUI (to enter the measurement settings) and a measurement function which gets called when pressing "START" in the GUI.
In both I use separate files for sub functions to keep it easier to read and maintain.
The file structure looks something like this
C:/../folder/+measure/measure.m
C:/../folder/+measure/getData.m
C:/../folder/+measure/plot.m
C:/../folder/+measure/evalutate.m
C:/../folder/+measureGUI/getGuiData.m
C:/../folder/+measureGUI/calcLimits.m
C:/../folder/+measureGUI/saveGuiState.m
C:/../folder/+measureGUI/loadGuiState.m
C:/../folder/+measureGUI/background.png
C:/../folder/+measureGUI/guiState.mat
C:/../folder/measureGUI.fig
C:/../folder/measureGUI.m
This works, if I'm executing the measureGUI.m in "folder".
The current settings in the GUI are saved in the guiState.mat file when closing the GUI in saveGuiState.m
filename = '+autoProberGUI/guiState.mat';
save(filename, 'guiState');
And loaded (by loadGuiState.m) the next time the GUI gets opened.
Now I have to put the finished program on a network drive and add the folder to my matlab search path to call measureGUI.m.
The program works but it can't save or load the guiState.mat due to the relative path (I guess the path is relative to the folder I'm currently in, and not the folder the calling function is in).
I think I could include the subfolder to the search path or use an absolute path in filename. But both solutions seem to me to be not the proper way.
Is there a way to have relative paths to the file from where the function is located on the drive? Meaning relative to
I:/..NetworkDrive../folder/+measureGUI/saveGuiState.m
instead of relative from where I call measureGUI.m
(Sorry for the poor English, I hope it is not too confusing)

You can use pwd to get the full path to you current working directory.
Then you can concatenate with [pwd '/folder/+measureGUI/saveGuiState.m'].
To locate the function you can use which.

Related

MATLAB - Get current path and then use it to navigate to a different folder

I have a bunch of codes that are currently stored on my local machine. There are two folders, one called "Resources" and another called "src". There is one main script that needs to be run called "main.m" in "src" which calls files from "Resources".
If I copy this whole thing onto a new computer, the paths will change and MATLAB may not be able to find "Resources" anymore. I know that relative to "main.m", I need to go up one level and then into "Resources".
What is the best way of getting MATLAB to point to "Resources"?
I am currently trying along the lines of
P = mfilename('fullpath')
which gives the path for main.m. Now, I want to navigate from here, one folder up and then into "Resources". Or if there is a better way, please let me know.
Eventually, I want to extend it to work for multiple folders "Resources1", "Resources2" etc. so MATLAB needs to be able to navigate to the right folder.
You can get it like:
fullfile(fileparts(mfilename('fullpath')), '..', 'Resources');
Explanation:
mfilename('fullpath') will return the full path and name of the
M-file in which the call occurs, without the extension
fileparts will return the path of the passed file (only the containing directory)
fullfile will build the full directory specification from the folder names passed (Note: '..' always means the parent directory)
Based on this it is quite simple to write a function that gets the sibling directory of the directory containing the file:
getSiblingOfParentDirectory.m
function siblingDirPath = getSiblingOfParentDirectory(filepath, siblingDirName)
siblingDirPath = fullfile(fileparts(filepath), '..', siblingDirName);
end
then to use it in an M-file:
for i = 1:3
disp(getSiblingOfParentDirectory(mfilename('fullpath'), ['Resources', num2str(i)]));
end
Sample output:
D:\pathtest\Resources1
D:\pathtest\Resources2
D:\pathtest\Resources3
You can try the following:
ResourcesFolder = strrep(mfilename('fullpath'), 'src\main', 'Resources');
addpath(ResourcesFolder);
%%Your code here where you need those files
rmpath(ResourcesFolder);
Which is fully dependant on the names of your folders & files of course. Basically "addpath" enables you to access the files in the mentioned directory by adding it to the search path, and "rmpath" does the exact opposite.
Also, if you literally want to navigate to a folder present on one level up, you can execute the following:
cd ..\Resources
Which goes one level up, searches for the folder 'Resources', then changes the current directory to that folder .

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.

temporary remove all of the added paths in matlab

I have added a lot of paths to matlab and now I want to share my code, but I don't know exactly which function (in which path) I should add to my shared code. Each time I need to add a missing function and it is really bothering for me and the users who are using the code.
So, I would like to restore the matlab path to its original case. Is there any way to do this in matlab? I also want to keep a backup of my current added path in a .m file and use it later when I am done.
To restore the path to default value - http://www.mathworks.com/help/matlab/ref/restoredefaultpath.html
restoredefaultpath sets the search path to include only folders for
MathWorks® installed products. Use restoredefaultpath when you are
having problems with the search path.
restoredefaultpath; matlabrc sets the search path to include only
folders for MathWorks installed products and corrects search path
problems encountered during startup.
And to save the current path - http://www.mathworks.com/help/matlab/ref/savepath.html
savepath updates the MATLAB® search path for all users on the system
so that the path can be reused in a future session. savepath saves the
search path to the pathdef.m file that MATLAB located at startup, or
to the current folder if a pathdef.m file exists there.
Or you can just store path in variable p = path; and restore it later path(p);. If the path is saved into pathdef.m the call of pathdef returns the string that can be used to set the saved path.

Does matlab have a matlabrc file?

Today I stumbled upon this thread:
http://www.mathworks.com/matlabcentral/newsreader/view_thread/112560
The question is basically how to make Matlab read your startup.m file regardless of where
you start your matlab session.
One of the solutions offered was:
One solution would be to ask the system administrator to add a few lines
to "matlabrc.m" that adds some pre-determined folder in the user's home
directory to the MATLAB path (say, ~/.matlabstart). Then each user can
have their own "startup.m" file inside this folder.
What I ended up doing in my system (OS X) was to add a startup.m file in:
/Applications/MATLAB_R2011a.app/toolbox/local/
In this startup.m file I added:
if exist([getenv('HOME') '/.matlabrc/startup.m'])
run([getenv('HOME') '/.matlabrc/startup.m']);
end
That way users have the option of creating the hidden folder ~/.matlabrc and inside it they can put the file startup.m. In this startup file they can tell matlab what to execute whenever they start Matlab regardless of the directory where they started it. An example of what I added to my own personal startup.m file is
addpath(genpath('/Users/jmlopez/matlabcode/'))
Now I can add as many folders inside that directory and all of them will be added
to the path every time I start Matlab automatically without having to modify the path.
The question is: Did Matlab already provided a special file like the one I created or did I just go through all this trouble to accomplish what I wanted? If the answer is the second option I gave, then, why doesn't Matlab provide this? It is such a pain in the ass to add directories to the Matlab path whenever you do not have admin permissions and I do not want to carry my startup.m file to every directory I go to. Can someone shed some light into this please?
You can save the pathdef file (which stores all the paths you add) to a custom directory. The problem however is that when matlab starts, it doesn't automatically know which custom directory you used in the previous session.
But that's where the MATLABPATH environment variable comes in. Because this allows to set the matlab starting path yourself. In linux this is simply done by setting this environment variable MATLABPATH before starting matlab (from a terminal / in your .bashrc / ...)
export MATLABPATH=$HOME/.matlab
This way you can let all users have their own pathdef file, which solves the problem of having to add them manually at startup.
EDIT
I tested out if adding startup.m to that MATLABPATH directory worked, ie: does matlab run that startup file? ... and it does. I think it doesn't work for you, because there is another startup.m file in some other (higher priority) directory (probably matlabroot), so that gets precedence. My only startup file is in MATLABPATH, so there is only one choice.
EDIT2
Nope, I added startup to matlabroot directory, and still my own startup file in .matlab gets run. Are you sure you set the MATLABPATH correctly before you started matlab?