adding functions to path

27 views (last 30 days)
ali hassan
ali hassan on 21 Sep 2020
Answered: Walter Roberson on 21 Sep 2020
% adds subfolder with functions to PATH
[p,n,e] = fileparts(mfilename('fullpath'));
addpath([p '/functions']);
addpath([p '/test']); % only required for the test setups
  3 Comments
Sindar
Sindar on 21 Sep 2020
"this is the code and i want to understand line by line that what is it doing?" was a tag
ali hassan
ali hassan on 21 Sep 2020
yes i want to understand it line by line plzz

Sign in to comment.

Answers (2)

Rik
Rik on 21 Sep 2020
Start with the documentation. It is one of the major advantages of Matlab over competing platforms. Do you understand what these three functions do? Then it is obvious what these lines do. If you don't, you should start with reading the documentation for each of them.
doc fileparts
doc mfilename
doc addpath
I would also suggest modifying this slightly: this code assumes the file separator is /, which is not always true. It is also good practice to add your custom functions to the bottom of the path, so they don't interfere with built-in functions.
% adds subfolder with functions to PATH
[p,n,e] = fileparts(mfilename('fullpath'));
addpath([p filesep 'functions'],'-end');
addpath([p filesep 'test'],'-end'); % only required for the test setups
Instead of using filesep you could also use fullfile to create the full path.

Walter Roberson
Walter Roberson on 21 Sep 2020
The first line is a comment.
The second file picks out the full name of the file that contains the executing code (mfilename('fullpath')) and splits it into directory (stored in p), filename (stored in n), and extension (stored in e). It ignores the filename and extension after that.
The code then constructs a directory name by adding the sub-directory name 'functions' to the name of the directory that the code was in, and it adds that functions directory to the path.
The code then constructions a directory name by adding the sub-directory name 'test' to the name of the directory that the code was in, and it adds that test directory to the path.

Categories

Find more on Search Path in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!