How to call a function placed in another directory in Matlab?

I have a huge project made in MATLAB, with 15-18 script files. It is very difficult to understand the whole code. I thought that if I can put some scripts in another folder, it will become very clear to understand and maintain the code. Is it possible to do this?

Consider the directory structure below:

enter image description here

How can I call a function from main.m that fits in func.m in Folder 1 ?

+6
source share
1 answer

Manual solution

Do the following:

  • Right-click the folder located on top of the hierarchy.
  • click "Add to Path"
  • Click on selected folders and subfolders

At this point, your scripts will be able to identify any function or script that is located in one of the internal subfolders that you have selected. In addition, you can call any script and function that you would like by simply typing its name on the command line.

Code solution

Instead of doing it manually, you can also add folders and subfolders to the path using the following code:

  addpath(genpath(<path to your directory>)) 

Example

Tree structure of current Matlab path

enter image description here

You can add functions and scripts from folder 1 to the path by writing the following code:

 addpath(genpath('Folder 1')) 

Or using the option "Add folders and subfolders" in the menu:

enter image description here

After that, you can call func directly from the main

+9
source

All Articles