- MATLAB 2020数学计算从入门到精通
- 林凤涛等编著
- 1523字
- 2025-02-22 21:35:20
2.1 文件路径
任何一个文件的操作(如文件的打开、创建、读写、删除、复制等),都需要确定文件在磁盘中的位置。MATLAB与C语言一样,也是通过文件路径(文件夹位置)来定位文件的。不同的操作系统对路径的格式有不同的规定,但大多数的操作系统都支持树状目录结构,即有一个根目录(Root),在根目录下,可以存在文件和子目录(Sub Directory),子目录下又可以包含各级子目录及文件。
路径下的实际目录取决于文件的格式。
在Windows系统下,一个有效的路径格式如下。
drive:\<dir…>\<file or dir>
其中,<drive:>是文件所在的逻辑驱动器盘符,<dir…>是文件或目录所在的各级子目录,<file or dir>是所要操作的文件或目录名。MATLAB的路径输入必须满足这种格式要求。
当前文件夹是MATLAB用于查找文件的参考位置。该文件夹也可称为当前目录、当前工作文件夹或现有工作目录。
在MATLAB中,除了可以利用“当前文件夹”工具栏查看当前文件夹外,还可以执行命令,更改或显示当前文件夹。
1.显示搜索路径
MATLAB的操作是在它的搜索路径(包括当前路径)中进行的,如果调用的函数在搜索路径之外,MATLAB就会认为该函数不存在。初学者往往会遇到这种问题,明明自己编写的函数在某个路径下,但MATLAB却报告此函数不存在。其实只要把程序所在的目录扩展成为MATLAB的搜索路径就可以了。
搜索路径是文件系统中所有文件夹的子集。MATLAB使用搜索路径来高效地定位用于Math-Works产品的文件。
默认的MATLAB搜索路径是MATLAB的主安装目录和所有工具箱的目录,用户可以通过以下几种形式查看搜索路径。
1)在MATLAB中,path命令用于文件的搜索路径,该命令的使用格式见表2-1。
表2-1 path命令的使用格式

例2-1: 显示MATLAB下的搜索路径。
解: MATLAB程序如下。


2)在命令窗口输入命令pathtool进入搜索路径设置对话框,如图2-1所示。单击“添加文件夹”按钮,或者单击“添加并包含子文件夹”按钮,进入文件夹浏览对话框。前者只把某一目录下的文件包含进搜索范围而忽略子目录,后者将子目录也包含进来。最好选择后者以避免一些可能的错误。

图2-1 “设置路径”对话框
在文件夹浏览对话框中,选择一个已存在的文件夹,或者新建一个文件夹,然后在“设置路径”对话框中单击“保存”按钮就将该文件夹保存进搜索路径了。
在MATLAB中,userpath命令用于查看或更改默认用户工作文件夹,该命令的使用格式见表2-2。
表2-2 userpath命令的使用格式

例2-2: 查看userpath文件夹。
解: MATLAB程序如下。


在MATLAB中,pathsep命令用于显示带分隔符的搜索路径,该命令的使用格式见表2-3。
表2-3 pathsep命令的使用格式

2.搜索路径文件夹
搜索路径上的文件夹顺序十分重要。当在搜索路径上的多个文件夹中出现同名文件时,MAT-LAB将使用搜索路径中最靠前的文件夹中的文件。
在MATLAB中,addpath命令用于从搜索路径中添加文件夹,不仅可以添加搜索目录,还可以设置新目录的位置。该命令的使用格式见表2-4。
表2-4 addpath命令的使用格式

例2-3: 添加新的搜索路径。
解: MATLAB程序如下。


在MATLAB中,savepath命令用于保存当前搜索路径,该命令的使用格式见表2-5。
表2-5 savepath命令的使用格式

在MATLAB中,rmpath命令用于从搜索路径中删除文件夹,该命令的使用格式见表2-6。
表2-6 rmpath命令的使用格式

例2-4: 从搜索路径中删除文件夹。
解: MATLAB程序如下。



在MATLAB中,genpath命令用于生成路径名称,输出由MATLAB所有搜索路径连接而成的长字符串,该命令的使用格式见表2-7。
表2-7 genpath命令的使用格式

3.确定文件和文件夹是否在搜索路径下
在MATLAB中,what命令列出当前文件夹的路径以及在当前文件夹中找到的与MATLAB相关的所有文件和文件夹。该命令的使用格式见表2-8。
表2-8 what命令的使用格式

例2-5: 列出路径、文件和文件夹信息。
解: MATLAB程序如下。


在MATLAB中,which命令显示当前文件夹的路径,以及在当前文件夹中找到的相应文件的完整路径。该命令的使用格式见表2-9。
表2-9 which命令的使用格式

如果item是一个重载的函数或方法,则which item只返回找到的第一个函数或方法的路径。
例2-6: 列出路径、文件和文件夹信息。
解: MATLAB程序如下。

