## 数组类型

### 多维数组

MATLAB® 环境中的多维数组是具有多个下标的数组。创建多维数组的一种方法是调用具有多个参数的 `zeros``ones``rand``randn`。例如，

`R = randn(3,4,5);`

MATLAB 与丢勒的 4 阶幻方矩阵版本的区别在于交换了两个列。通过交换列，可以生成许多不同的幻方矩阵。语句

`p = perms(1:4);`

```A = magic(4); M = zeros(4,4,24); for k = 1:24 M(:,:,k) = A(:,p(k,:)); end```

```size(M) ans = 4 4 24```

`sum(M,d)`

`sum(M,1)`

`34 34 34 34`

`sum(M,2)`

```34 34 34 34```

`S = sum(M,3)`

```S = 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204 204```

### 元胞数组

MATLAB 中的元胞数组是以其他数组的副本为元素的多维数组。使用 `cell` 函数可以创建空矩阵的元胞数组。但是，更普遍的做法是，通过将其他内容的集合括入花括号 `{}` 中来创建元胞数组。花括号还可以与下标配合使用，以便访问各个元胞的内容。例如，

`C = {A sum(A) prod(prod(A))}`

```C = [4x4 double] [1x4 double] [20922789888000]```

```M = cell(8,1); for n = 1:8 M{n} = magic(n); end M```

```M = [ 1] [ 2x2 double] [ 3x3 double] [ 4x4 double] [ 5x5 double] [ 6x6 double] [ 7x7 double] [ 8x8 double]```

`M{4}`

### 字符与文本

`s = 'Hello'`

`a = double(s)`

```a = 72 101 108 108 111```

`s = char(a)`

`F = reshape(32:127,16,6)';`

```char(F) char(F+128)```

`h = [s, ' world']`

```h = Hello world```

`v = [s; 'world']`

```v = Hello world```

`S = char('A','rolling','stone','gathers','momentum.')`

```S = A rolling stone gathers momentum.```

`C = {'A';'rolling';'stone';'gathers';'momentum.'}`

```C = 'A' 'rolling' 'stone' 'gathers' 'momentum.'```

`C = cellstr(S)`

`S = char(C)`

### 结构体

```S.name = 'Ed Plum'; S.score = 83; S.grade = 'B+'```

```S = name: 'Ed Plum' score: 83 grade: 'B+'```

```S(2).name = 'Toni Miller'; S(2).score = 91; S(2).grade = 'A-';```

```S(3) = struct('name','Jerry Garcia',... 'score',70,'grade','C')```

```S = 1x3 struct array with fields: name score grade```

`S.score`

`S(1).score, S(2).score, S(3).score`

```scores = [S.score] scores = 83 91 70 avg_score = sum(scores)/length(scores) avg_score = 81.3333```

```names = char(S.name) names = Ed Plum Toni Miller Jerry Garcia```

```names = {S.name} names = 'Ed Plum' 'Toni Miller' 'Jerry Garcia'```

```[N1 N2 N3] = S.name N1 = Ed Plum N2 = Toni Miller N3 = Jerry Garcia```

#### 动态字段名称

`structName.(expression)`

`structName.(expression)(7,1:25)`

```function avg = avgscore(testscores, student, first, last) for k = first:last scores(k) = testscores.(student).week(k); end avg = sum(scores)/(last - first + 1);```

```testscores.Ann_Lane.week(1:25) = ... [95 89 76 82 79 92 94 92 89 81 75 93 ... 85 84 83 86 85 90 82 82 84 79 96 88 98]; testscores.William_King.week(1:25) = ... [87 80 91 84 99 87 93 87 97 87 82 89 ... 86 82 90 98 75 79 92 84 90 93 84 78 81];```

```avgscore(testscores, 'Ann_Lane', 7, 22) ans = 85.2500 avgscore(testscores, 'William_King', 7, 22) ans = 87.7500```