Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a large project coded in MATLAB, with 15-18 scripts. It is becoming very challenging to understand the whole code. I was thinking that if I can put some scripts in another folder, it will become very straightforward to understand and maintain the code. Is it possible to do that?

Consider the below directory structure:

enter image description here

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

like image 653
Atinesh Avatar asked Jun 26 '16 15:06

Atinesh


People also ask

How do you call a method in another method in MATLAB?

Answers (1) There are two ways to call another method function from the same class. First, you can use a dot/period to access the method from the class variable. Second, you can simply call the function and pass the class object as an argument.

How do you call a nested function in MATLAB?

You must call a nested function either directly by name (without using feval ), or using a function handle that you created using the @ operator (and not str2func ). All of the variables in nested functions or the functions that contain them must be explicitly defined.


1 Answers

Manual solution

Perform the following:

  1. Right click on the folder which is on top of the hierarchy.
  2. click on Add to path
  3. Click on selected folders and subfolders

At this stage, your scripts will be able to identify any function or script which resides in one of the inner subfolders which you chose. In addition you can call any script and function you would like by simply typing it's name in the command line.

Code solution

Instead of doing it manualy, it is also possible to add folders and subfolders into path by using the following code:

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

Example

The tree structure of the current Matlab path

enter image description here

You can add the functions and scripts from Folder 1 into path by either writing the following code:

addpath(genpath('Folder 1'))

Or by using 'Adding folders and subfolders' option from the menu:

enter image description here

After doing so, it is possible to call func straight from main

like image 138
ibezito Avatar answered Oct 10 '22 10:10

ibezito