访问元胞数组中的数据

基本索引

```C = {'one','two','three'; 100,200,rand(3,3)}```
```C=2×3 cell array {'one'} {'two'} {'three' } {[100]} {[200]} {3x3 double} ```

`C2 = C(1:2,1:2)`
```C2=2×2 cell array {'one'} {'two'} {[100]} {[200]} ```

`R = C{2,3}`
```R = 3×3 0.8147 0.9134 0.2785 0.9058 0.6324 0.5469 0.1270 0.0975 0.9575 ```
`C{1,3} = 'longer text in a third location'`
```C=2×3 cell array {'one'} {'two'} {'longer text in a third location'} {[100]} {[200]} {3x3 double } ```

`C(1,1:2) = {'first','second'}`
```C=2×3 cell array {'first'} {'second'} {'longer text in a third location'} {[ 100]} {[ 200]} {3x3 double } ```

从多个元胞读取数据

MATLAB® 中的大多数数据处理函数都是在具有一致数据类型的矩形数组上操作的。由于元胞数组可以包含多种类型和大小，因此有时必须在处理数据之前先从元胞中提取和合并数据。本节描述一些常见的情况。

特定元胞中的文本

`ts = strfind(C(1,:),'t')`
```ts=1×3 cell array {[5]} {0x0 double} {[8 11 18 28]} ```

特定元胞中的数值

• 将这些元胞的内容合并成单个数值数组，然后处理该数组。

• 分别处理单个元胞。

`v = cell2mat(C(2,1:2))`
```v = 1×2 100 200 ```

`len = cellfun(@length,C(2,:))`
```len = 1×3 1 1 3 ```

具有未知索引的元胞中的数据

• 使用逻辑索引找到满足特定条件的所有元素，然后处理这些元素。

• 使用 `for``while` 循环一次只检查并处理一个元胞。

`idx = cellfun(@ischar,C)`
```idx = 2x3 logical array 1 1 1 0 0 0 ```

`len = strlength(C(idx))`
```len = 3×1 5 6 31 ```

```n = 0; for k = 1:numel(C) if ischar(C{k}) && contains(C{k},"t") n = n + 1; txt(n) = string(C{k}); end end txt```
```txt = 1x2 string "first" "longer text in a third location" ```

对多个元胞进行索引

`C{1:2,1:2}`

`C{1,1}, C{2,1}, C{1,2}, C{2,2}`.

`[v1,v2,v3,v4] = C{1:2,1:2}`
```v1 = 'first' ```
```v2 = 100 ```
```v3 = 'second' ```
```v4 = 200 ```

`v = [C{2,1:2}]`
```v = 1×2 100 200 ```

`t = cell2table(C(2,:),VariableNames=C(1,:))`
```t=1×3 table first second longer text in a third location _____ ______ _______________________________ 100 200 {3x3 double} ```

对元胞内的数组进行索引

`C{2,3}(2,:)`
```ans = 1×3 0.9058 0.6324 0.5469 ```

```c = {'A'; ones(3,4)}; s = struct("f1",'B',"f2",ones(5,6)); C = {c,s}```
```C=1×2 cell array {2x1 cell} {1x1 struct} ```

`A1 = C{1}{2}`
```A1 = 3×4 1 1 1 1 1 1 1 1 1 1 1 1 ```
`A2 = C{2}.f2`
```A2 = 5×6 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 ```

`C{1}{2}{3}`

`C{4}.f1.f2(1)`

`C{5}.f3.f4{1}`