介绍性示例(详见元胞数组的基本用法)演示了如何创建软件包含当前可用变量的元胞数组。然而,在许多情况下,创建一个元胞数组,然后用数据填充它是很有用的。
这里的cell函数返回给定大小的元胞数组,其中包含空矩阵。此函数类似于zeros用于创建新数字数组的函数。以下示例创建一个包含空矩阵的2乘2元胞数组
c = cell (2,2)
⇒ c =
{
[1,1] = [](0x0)
[2,1] = [](0x0)
[1,2] = [](0x0)
[2,2] = [](0x0)
}
就像数字数组一样,元胞数组也可以是多维的。这里的cell函数接受任意数量的正整数来描述返回的元胞数组的大小。也可以通过正整数的向量来设置元胞数组的大小。在以下示例中,将创建两个大小相等的元胞数组,并显示第一个的大小
c1 = cell (3, 4, 5);
c2 = cell ( [3, 4, 5] );
size (c1)
⇒ ans =
3 4 5
可以看出size函数也适用于元胞数组。其他描述对象大小的函数也是如此,例如length, numel,rows和columns.
作为创建空元胞数组然后填充它们的替代方案,可以使用num2cell, mat2cell和cellslices函数。
C = num2cell (A) ¶C = num2cell (A, dim) ¶转换数字矩阵A到元胞数组。
当否dim的每个元素A成为输出中的1x1元素C.
如果dim则定义的各个元素C包含中的所有元素A沿着指定的尺寸。dim也可以是应用相同规则的维度的avector。
例如
x = [1,2;3,4]
⇒
1 2
3 4
## each element of A becomes a 1x1 element of C
num2cell (x)
⇒
{
[1,1] = 1
[2,1] = 3
[1,2] = 2
[2,2] = 4
}
## all rows (dim 1) of A appear in each element of C
num2cell (x, 1)
⇒
{
[1,1] =
1
3
[1,2] =
2
4
}
## all columns (dim 2) of A appear in each element of C
num2cell (x, 2)
⇒
{
[1,1] =
1 2
[2,1] =
3 4
}
## all rows and cols appear in each element of C
## (hence, only 1 output)
num2cell (x, [1, 2])
⇒
{
[1,1] =
1 2
3 4
}
详见: mat2cell.
C = mat2cell (A, dim1, dim2, …, dimi, …, dimn) ¶C = mat2cell (A, rowdim) ¶转换矩阵A到元胞数组C.
每个维度参数(dim1, dim2等)是一个元素向量,它指定如何在输出中的新元素中划分该维度的元素C。中的元素数量i-维度是size (A, i)。因为中的所有元素A必须分区,有一个要求sum (dimi) == size
(A, i)。输出数组的大小C是numel(dim1)xnumel(dim2)x…x数字(dimn).
给定一维参数,rowdim,输出按指定划分为行。所有其他维度都没有划分,因此所有列(dim 2)、页(dim 3)等都出现在每个输出元素中。
示例
x = reshape (1:12, [3, 4])'
⇒
1 2 3
4 5 6
7 8 9
10 11 12
## The 4 rows (dim1) are divided in to two cell elements
## with 2 rows each.
## The 3 cols (dim2) are divided in to three cell elements
## with 1 col each.
mat2cell (x, [2,2], [1,1,1])
⇒
{
[1,1] =
1
4
[2,1] =
7
10
[1,2] =
2
5
[2,2] =
8
11
[1,3] =
3
6
[2,3] =
9
12
}
## The 4 rows (dim1) are divided in to two cell elements
## with a 3/1 split.
## All columns appear in each output element.
mat2cell (x, [3,1])
⇒
{
[1,1] =
1 2 3
4 5 6
7 8 9
[2,1] =
10 11 12
}
sl = cellslices (x, lb, ub, dim) ¶给定一个数组x,此函数从索引向量确定的数组中生成切片的元胞数组lb, ub,分别用于下限和上限。
换句话说,它等效于以下代码:
n = length (lb);
sl = cell (1, n);
for i = 1:length (lb)
sl{i} = x(:,...,lb(i):ub(i),...,:);
endfor
索引的位置从dim如果未指定,则沿第一个非奇异维度进行切片。
详见: cell2mat, cellindexmat, cellfun.
版权所有 © 2024-2025 Octave中文网
ICP备案/许可证号:黑ICP备2024030411号-2