
2.1.3 字符类型
在MATLAB中,将文本当作特征字符串或简单地当作字符串。字符串能够显示在屏幕上,也可以用来构成一些命令,这些命令在其他的命令中用于求值或被执行。
在MATLAB中,可能会遇到对字符和字符串的操作。一个字符串是存储在一个行向量中的文本,这个行向量中的每个元素代表一个字符。实际上,元素中存放的是字符的内部代码,即ASCII码。
当在屏幕上显示字符变量的值时,显示出来的是文本,而不是ASCII码。由于字符串是以向量的形式存储的,因此可以通过下标对字符串中的任何一个元素进行访问。对于字符矩阵,也可以通过下标索引进行访问,但是矩阵的每行字符数必须相同。
字符串一般是ASCII码的数值数组,作为字符串表达式进行显示。
例2-6:字符串属性示例。
在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

一个字符串是由单引号引起来的简单文本。字符串中的每个字符都是数组中的一个元素,字符串存储要求每个字符占8字节,如同MATLAB的其他变量。
因为ASCII码字符只要求占1字节,所以这种存储要求是浪费空间的,所分配的的存储空间无用。然而,对字符串保持同样的数据结构可以简化MATLAB的内部数据结构。MATLAB中给出的字符串操作并不是MATLAB的基本特点,但这种表达是方便和可接受的。
为了了解字符串的ASCII码表达,只需对字符串执行一些算术运算。最简单和计算上最有效的方法是取数组的绝对值。
例2-7:字符串的ASCII码表达。
在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在本例中,给字符串加零并没有改变它的ASCII码表达。因为字符串是数值数组,所以可以用MATLAB中所有可利用的数组操作工具对其进行操作。
例2-8:字符串数组的索引示例。
在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在本例中,字符串像数组一样进行编址。这里元素7~10包含单词good。
字符串中的单引号是由两个连续的单引号来表示的。
例2-9:字符串中的单引号。
在命令行窗口中输入:

输出结果:

字符串的连接可以通过直接将字符串数组连接起来来实现。
例2-10:字符串的连接。
在命令行窗口中输入:

输出结果:
