- MATLAB 8.5基础教程
- 杨德平 孙显录 管殿柱等
- 956字
- 2025-02-17 23:09:44
3.1 字符串数组
字符串是指1×n的字符数组,也可以是多行多列的字符串数组。MATLAB提供了多种字符串操作,包括字符串的创建、查找及与数值之间的转换等。
3.1.1 串数组的生成
字符串是存储在一个行向量中的文本,行向量中的每一个元素代表一个字符。在MATLAB中创建字符串的方法具体如下。
1.直接输入法
直接用单引号输入,例如在命令行窗口输入:

运行结果如下:

字符串内可包含字母、数字、特殊字符以及中文字等内容。若在单引号外加大括号{}也可以显示字符串,例如:

从结果来看,显示的内容有单引号标示,而单引号法显示的却只是文本。
2.利用命令disp法

例如:

运行结果如下:

3.利用命令char法

例如:

4.利用命令input法

如果变量in是's',则输入的内容以字符串的形式进行保存。
例如,在命令行窗口中输入:

运行结果如下:

然后在“x:”的后面输入一个数6,按<Enter>键即得:

此时数值6以变量x的形式显示在工作区Workspace内。若执行如下命令:

此时数字6以字符串的形式保存在工作区Workspace内。
5.在字符串中用两个单引号来表示一个单引号
例如:

3.1.2 串数组的访问和大小
1.串数组的访问
字符串的存储是将其中字符按顺序单一存放的,且存放的是字符的ASCII码。当在屏幕上显示字符变量的值时,显示出来的是文本,而不是ASCII数值。由于字符串是以向量的形式来存储的,所以可以通过它的下标对字符串中的任何一个元素进行访问。
例如,对上面定义的字符串Book,输入命令:

2.字符串的长度
字符串的长度可用length()和size()函数来确定,例如:

3.字符串的查找
在字符串中寻找某个字符串,可用函数findstr()来实现。

例如,在上面定义的字符串Book中查找A所在的位置:

注:字符串和要查找的字符串的位置可以互换,且其结果相同。因此,S1、S2哪个在前都可。
3.1.3 多行串数组的创建
1.多行串数组的直接输入
字符串数组可以是多行多列的数组,但必须保证每一行都有相同的列数。若字符串长度不一样,需要用空格填充,保证所有行的长度都相同。例如:

2.利用串操作函数创建多行串数组
利用函数char()、strvcat()创建多行串数组,每行的字符串长度可以不同。例如:

3.1.4 字符串数组的转换
1.字符串转换成矩阵
将字符串转换成矩阵的函数为str2mat()。例如:

2.字符串与数值的转换
利用str2num()和num2str()实现字符串与数值的相互转换。例如:

注:虽然S的显示结果与X看上去一样,但其含义不同。X是数组,S是字符串。同样字符串可以转化为数组,例如:
