
2.1.7 元胞数组类型
1.概述
元胞(Cell)数组是一种无所不包的广义矩阵。组成元胞数组的每个元素称为一个单元。每个单元可以包括一个任意数组,如数值数组、字符串数组、结构体数组或另外一个元胞数组,因而每个单元可以具有不同的尺寸和内存占用空间。
○ 注意
与一般的数值数组一样,元胞数组的维数不受限制,可以为一维、二维或多维。
MATLAB中使用元胞数组的目的在于,它可以把不同类型的数据归并到一个数组中。
○ 注意
元胞数组的创建有两种方法:使用赋值语句创建元胞数组和利用cell函数创建空元胞数组。
(1)使用赋值语句创建元胞数组。与一般数组不同的是,元胞数组使用花括号“{}”来创建,使用逗号“,”或空格来分隔每个单元,使用分号“;”来分行。
例2-18:创建元胞数组。
在命令行窗口中输入:

程序运行结果如下:

(2)利用cell函数创建空元胞数组。
cell函数的调用格式如下:

该函数创建一个m×n的空元胞数组,每个单元均为空矩阵。
例2-19:创建空元胞数组。
在命令行窗口中输入:

程序运行结果如下:

与一般的数值数组一样,元胞数组的内存空间也是动态分配的。因此,使用cell函数创建空元胞数组的主要目的是为该元胞数组预先分配连续的存储空间,以节约内存,提高执行效率。
2.元胞数组的寻访
在元胞数组中,单元和单元中的内容是两个不同范畴的东西,因此,寻访单元和单元中的内容是两种不同的操作。MATLAB为上述两种操作设计了相对应的操作对象:单元外标识(Cell Indexing)和单元内编址(Content Addressing)。
对于元胞数组C,C(m,n)指的是元胞数组中第m行第n列的单元,而C{m,n}指的是元胞数组中第m行第n列单元中的内容。
例2-20:元胞数组的寻访。
在命令行窗口中依次输入以下命令:

得到的结果如下:

3.元胞数组的操作
元胞数组的操作包括合并/删除元胞数组中的指定单元、改变元胞数组的形状等。
(1)元胞数组的合并。
例2-21:元胞数组的合并。
在命令行窗口中依次输入以下命令:


得到的结果如下:

(2)元胞数组中指定单元的删除。
如果要删除元胞数组中某个指定单元,则只需将空矩阵赋给该单元,即:

例2-22:有一个元胞数组C,删除其中的某个单元。
在命令行窗口中输入下列命令:

得到的结果如下:

(3)使用reshape函数改变元胞数组的形状。
reshape函数的调用格式为:

该函数将元胞数组C改变成一个具有M行N列的新元胞数组。
例2-23:将例2-22中的元胞数组C(1×4)改变成newC(4×1)。
在命令行窗口中输入:

得到的结果如下:
