简体   繁体   English

如何在Matlab中调用放在另一个目录中的函数?

[英]How to call a function placed in another directory in Matlab?

I have a large project coded in MATLAB , with 15-18 scripts . 我有一个用MATLAB编写的大型项目,有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: 考虑以下目录结构:

在此输入图像描述

How can I call a function from main.m that is placed in func.m in Folder 1 ? 如何从位于Folder 1中的func.m中的main.m调用函数?

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 当前Matlab路径的树结构

在此输入图像描述

You can add the functions and scripts from Folder 1 into path by either writing the following code: 您可以通过编写以下代码将文件夹1中的函数和脚本添加到路径中:

addpath(genpath('Folder 1'))

Or by using 'Adding folders and subfolders' option from the menu: 或者使用菜单中的“添加文件夹和子文件夹”选项:

在此输入图像描述

After doing so, it is possible to call func straight from main 这样做之后,可以直接从main调用func

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM