Find location of current script (mlx-file) in MATLAB - matlab

I'm working on my MATLAB code in a number of different locations, and it would be really helpful if I could make the code aware of its location on the computer. Till now I worked with .m-files. For .m-files I found the following solutions:
%example 1
cd(fileparts(mfilename('fullpath')))
or
%example 2
tmp = matlab.desktop.editor.getActive;
cd(fileparts(tmp.Filename));
or
%example 3
S = dbstack('-completenames');
S(1).file
or
%example 4
which(mfilename)
But with MATLAB 2016a there comes a new feature called live script. And with that those solutions are not working anymore.
%For example I would like to do something like this
cd(MLX_FILELOCATION);
%or
which(mlxfilename)
(Edit III: Problem: I am not able to get the path/filelocation or name of the current opened/executed MATLAB-file. With *.m-files this is possible with the examples above. With *.mlx-files it is not possible anymore. And I prefere to use *.mlx-files instead of *.m-files.)
Outputs of the examples above executed in a *.mlx-file:
%example1: mfilename returns the path to the 'MatlabEvaluationHelper' in the 'AppData\Local\Temp'-folder
%example2: output is an empty array
%example3: same output as example1
%example4: same output as example1, because mfilename returns "MatlabEvaluationHelper"
Edit I:
My first goal is that I would like to change the "current folder" (-> "cd") to the path of the running script.
Why: In the same folder with the mlx-file I have for example .csv-files with data. And for example by tomorrow I have new folder. I copy the mlx_file and now I want to make sure that I don't use the csv-files from yesterday (because the current folder from yesterday is shown in the file browser of MATLAB) -> so I would like to change the "current folder" automatically with just copying the mlx-file into a new folder.
If there is a better practise for that, please let me know.
Thanks for helping
Edit II:
Example for a used workflow:
I programmed a MATLAB script. Saved it in folder "Dataset_ONE". Furthermure I copy "Dataset_ONE.csv"-file into the same folder. E.g. I now create a plot and save it as the "*.png" in folder "Dataset_ONE".
The day after I might have a second (a new and with that different) dataset "Datasset_TWO". I create a new folder "Dataset_TWO". Copy the MATLAB-files to the new folder. Open the MATLAB file there. Then, because of the default settings, MATLAB has changed the "Current Folder" to the new folder where I opened MATLAB.
But if I now open the MATLAB script in the first folder again (at the same time with the other dataset MATLAB script) I have to be careful about the current folder.
In this case it might be useful to have the described solution.

If what you want is some sort of way of preventing you running the wrong script on the wrong data without realising, then you could add a safety instruction at the top of each script, throwing an error if your current directory is not the same as the location of the script you're running. e.g.
>> assert (strcmp (pwd, '/absolute/path/to/my/script'));
As for loading the right data / saving to the right location, just load and save using absolute paths and there should be no confusion.

Related

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.

saving data from workspace to different dirrectory in matlab

I have a loop which my main script run through that. I wounder to save some of my variables in different directory every time that my loop is running. I have used following script but its not working:
for i=1:size(whisk, 1);
my codes is here and it creates variables in my workspace like [format, measurements].
the rest is what I wote to save this variables:
mkdir('C:\videos\results\', num2str(i));
dumvar=0; % As matlab has problem with data>2GB, then I use this 2 line code for saving
save('measurenments','dumvar','-v7.3');
save(fullfile('C:\videos\results\', num2str(i),'measurenments'));
clear all;
close all;
end
but Unfortunately its not work!!!!!!!!!!!
Any help would be appreciated.
Sam
Except that measurenments is wrongly spelled (correct spelling is measurements), there is not so strange that it does not work. The first call to save, saves the variable dumvar in the current folder, with the format v7.3. The second call to save, saves the whole workspace as a file fullfile('C:\videos\results\', num2str(i),'measurenments'). Try this,
save(fullfile('C:\videos\results\', num2str(i),'measurenments'),'dumvar','-v7.3');
However it seems as the folder fullfile('C:\videos\results\', num2str(i),'measurenments') does not exist since you only create the folder mkdir('C:\videos\results\', num2str(i))
. Then matlab cannot save anything there. Try either to save as fullfile('C:\videos\results\', [num2str(i),'measurenments']) or create the directory mkdir('C:\videos\results\', [num2str(i),'\','measurenments']);
`

Access data files from subfolder of current script directory

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');

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?

How to make matlab see functions defined in .m files?

I'm a total newbie to MATLAB but I have to write some code in it. I've had problems with making MATLAB see functions I've defined in external .m files. This is what I've done: I've created a file named, say, foo.m in my home dir with the following contents:
function [y] = foo(x)
% description
y = x + 1
When I run matlab (my home dir is matlab's workdir) it does not see foo function - it replies with standard ??? Undefined function or variable 'foo' message. BUT help foo or which foo return correct data printing help text and pointing on foo.m file respectively.
I must be missing something but I have no idea what it is. This is getting very annoying.
Oh, after several trial and error attempts I've managed to call that function. Unfortunately I can't remember the sequence of steps I've performed. Moreover after restarting matlab it returns to its usual 'Undefined function or variable' response.
I have 7.11.0.584 matlab running on linux.
MATLAB needs to be told which directories to search over to access those m-files. Clearly it cannot be left to search over your entire disk drives. The MATLAB search path is a list of directories that will be searched in specific order to find your functions.
help addpath
help pathtool
You should never put those files anywhere in the official MATLAB toolbox directories. Choose an entirely separate directory.
Finally, be careful not to name your own functions to match the names of existing MATLAB functions. Otherwise, your very next question here will be why your code does not work properly. This is a common cause of strange and confusing bugs.
It seems you're having some trouble with addpath. Try opening the file in the matlab editor and adding a break point in the file. If the file is not on Matlab's path, matlab should ask if you want to change directory or add the file to the path, choose add to the path.
If this doesn't work, try changing the current working directory (displayed in the main window) to the same location as the m file and calling the function. If this doesn't work you're either getting the name wrong ar there's possibly something wrong with your installation.
Occasionally matlab has problems if it does not have write permission to the directory the file's in, so check that too, i.e. make sure admin rights aren't required for the directory or m file.
Oh, and try:
clear functions
to reload all functions into memory.
The function needs to be in MATLAB's path. Use pathtool to tell MATLAB where to find your function. Note that if you name a function the same name as an existing function, MATLAB will use whichever function it finds first according to the order that the paths are listed as you see them in pathtool.
Although coming late but I hope it will help someone.
If in the folder where the function you are calling is residing, there is any other function with the same name as one of the functions from MATLAB toolboxes, then Matlab will not recognize its license and therefore will disable the whole folder from execution, no matter it is properly added to the path. The help will display though.
In order to check it, type:
which name_of_func.m
and you will get the path with "%Has no license available" message.
If it is your own function, you should not get this message but only the path.
Therefore, find the function in this folder which has the same name as a MATLAB toolbox functions, and rename it. I will solve the problem :).
Best Regards
Wajahat