Call a Matlab function not in working directory - matlab

Is it possible to have Matlab call a function that is not in the working folder?
For example, can I specify a path like .\bar\foo(arg1) and have the function execute? I have a number of helper functions that I want to use without clogging up my working directory.

Yes, you can use the command addpath to add the folders you need to the MATLAB path.

Related

Using Function from User-Defined Script in MATLAB

I have placed a MATLAB script "x.m" in the path of my current working directory. So the script is in folder "~/a" and my working directory is "~/a/b"
But MATLAB seems to be not recognizing that the single function 'x' in the script exists? I have named the file exactly the same as function, which works properly when I place the script in my exact working directory rather than just on the path of my working directory. I believe my version is MATLAB2016a, if that makes any difference. Before updating to MATLAB2016a, I had made a similar function and was able to use it properly with just putting the script in the path of my working directory.
Suggestions/solutions?
You can't just have a function in the parent directory and expect MATLAB to find it. There is a thing called the MATLAB path, which is the collection of directories MATLAB will search to find functions. You can add directories to it using addpath.

Calling user defined function anywhere? (matlab)

Where can i save my document "function.m", so i can call this function from any code in any path of my pc?
I already made some custom functions, but i dont know where to save those codes to be able to call them from any part.
Save them in a logical place where you can find them back. Then, use addpath to add that folder to MATLAB's search path, i.e. when you use a function it will try that folder as well to find it.
You can do this either per script, or edit startup.m with this, so that it's automatically included when MATLAB starts.
Alternatively to Adriaan's best practice answer, the fastest option is to save your function.m in the %USERPROFILE%/Documents/MATLAB directory on your PC ($home/Documents/MATLAB on Linux and Mac). This directory is on your MATLAB Search Path by default. This might be an acceptable solution if you use the function commonly across different projects.
Finally, there is a "manual" solution: Execute pathtool in MATLAB, add the directory containing your function.m via the GUI and hit save.

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!!

Executing a file or calling a function whose file is placed in another folder with MATLAB?

Tried Googling, but couldn't find anything.
I have a few files and folders in my current MATLAB folder.
One of those folders is called 'Map' and it has a 'map1.m' file which I want to call from my code in the current MATLAB folder.
In my code, I can't call it like this:
/Map/map1;
but I can do so like this:
cd Map;
map1;
cd ..;
Somehow the above method seems incorrect. Is there a more elegant way to do it?
You can run the file without adding the folder to your path manually, using the run command, which is specifically for such cases. From the documentation:
run is a convenience function that runs scripts that are not currently on the path.
You call your function/script as
run /Map/map1
If you want to run the function/script by merely entering its name and not with the full (or relative) path, then you should add the folder to your path.
As noted by #mutzmatron, you cannot use run to call functions with input/output arguments. So, unless if it's a script/function without input/output arguments, using run will not work and you'll have to add the folder to your path.
EDIT
Just as a matter of good coding practice, and to work in cases where your function has inputs/outputs, adding/removing the folder from your path is the correct way to go. So for your case,
addpath /Map
...
map1;
...
rmpath /Map
The important thing is that your function call is sandwiched between the addpath and rmpath commands. If you have functions of the same name in both folders, then you should sandwich it tighter i.e., a line before and a line after, so as to avoid conflicts.
Just add all those directories to the Matlab path with addpath like gnovice suggests. Then you'll be able to call the functions normally, and they'll be visible to which(), help(), depfun(), and the other Matlab meta-programming commands. You can put the addpath() calls in your startup.m file to have them automatically appear each time you start Matlab.
Changing the path with addpath/map1()/rmpath each time has some drawbacks.
It's a performance hit because you're adding path manipulation to each call.
Functions in different directories won't be able to see each other.
It'll be harder to write and debug functions because the path context in which they execute will change dynamically, and won't be the same as what you see when you're in the editor and the base workspace.
You need additional error handling code to make sure the path is properly restored if the called function errors out.
This won't work with the Matlab Compiler, if you want to deploy this code at some point.
And using run() or cd() yourself is ugly, because relative paths are going to have problems.
If you really want to separate the functions in the subdirectories so they can't "see" each other, you can make those directories namespaces by putting a "+" in front of their names, and then qualify the function calls with the namespace, like Map.map1().
Just to contribute to the path-altering debate...
One way to make it a bit "safer" is to write
% start of my code: create function handles
% to the functions I need:
try
cd Map
map1_func = #map1;
catch mexception
end
cd ..
This tries to preserve the current directory, and you get a handle to the function in a different directory.
Only thing is, this method won't work if map1 relies upon other functions in the Map directory.

How do I emulate 'include' behaviour in MATLAB?

In MATLAB I can define multiple functions in one file, with only the first defined function being visible external to that file. Alternatively, I can put each function in its own file and make them all globally visible through the path. I'm writing a menu driven application, where each menu item runs a different function. Currently, these are all in one big file, which is getting increasingly difficult to navigate. What I'd like to do is put groups of related functions into separate files.
I think I can do something like this by putting all the child functions into a separate directory and then adding the directory to the path in my parent function, but this feels a bit messy and inelegant.
Can anyone make a better suggestion?
Note: I'm most familiar with MATLAB 2006, but I'm in the process of upgrading to MATLAB 2009.
One suggestion, which would avoid having to modify the MATLAB path, is to use a private function directory. For example:
Let's say you have a function called test.m in the directory \MATLAB\temp\ (which is already on the MATLAB path). If there are local functions in test.m that you want to place in their own m-files, and you only want test.m to have access to them, you would first create a subdirectory in \MATLAB\temp\ called private. Then, put the individual local function m-files from test.m in this private subdirectory.
The private subdirectory doesn't need to be added to the MATLAB path (in fact, it shouldn't be added to the path for things to work properly). Only the file test.m and other m-files in the directory immediately above the private subdirectory have access to the functions it contains. Using private functions, you can effectively emulate the behavior of local functions (i.e. limited scope, function overloading, etc.) without having to put all the functions in the same m-file (which can get very big for some applications).
Maybe something like this,
function foobar
addpath C:\Include\ModuleX
%% Script file residing in ModuleX
some_func();
end
Of course, ModuleX will remain in your search path after exiting foobar. If you want to set it to the default path without restarting, then add this line:
path(pathdef)
See ADDPATH for more details.
You can use sub-folders that begin with "+" to separate functions into namespaces.
For example:
Place a function "bar" in the folder "+foo"
function bar()
print('hello world');
This function can be used as:
foo.bar() % prints hello world
More information can be found here:
What is the closest thing MATLAB has to namespaces?