这在 Matlab 中是非法的
a = [[1];[2 3]]
在允许这样做的语言中,这称为嵌套数组。
我在 Matlab 中找到了一种方法:
a = {[1];[2 3]}
这个叫什么?如何在无需编写大量代码的情况下以固定大小(例如 100)初始化这样的变量?
这在 Matlab 中是非法的
a = [[1];[2 3]]
在允许这样做的语言中,这称为嵌套数组。
我在 Matlab 中找到了一种方法:
a = {[1];[2 3]}
这个叫什么?如何在无需编写大量代码的情况下以固定大小(例如 100)初始化这样的变量?
它被称为单元阵列。
您使用命令初始化它cell
cellArray = cell(3,2); %# this makes a 3-by-2 cell array
存储不同对象集合的另一种方法是struct,您可以像这样初始化它
myStruct = struct('firstField',1,'secondField',[2 3])
与单元格相比,结构的优势在于字段是命名的,这使得处理和记录变得更加容易。如果您想经常操作数据,单元格可以非常方便地存储数据,因为您可以cellfun
与它们一起使用。我发现自己经常使用单元格将数据保存在函数中,但使用结构(或对象)在函数之间传递数据。
此外,如果您有一个数字列表并希望将它们分配给元胞数组的元素,您可以使用num2cell
,它将数组的每个元素分别放入元胞数组的一个元素中,或者mat2cell
,如果您想拆分排列不均匀。
a = {1,[2 3]}
相当于
b = mat2cell([1 2 3],[1 1],[1 2]);
或者,我可以通过键入来发现大括号的含义
help paren
哪个输出:
{ } 大括号用于形成元胞数组。它们类似于括号 [ ],只是保留了嵌套级别。{magic(3) 6.9 'hello'} 是一个包含三个元素的元胞数组。{magic(3),6.9,'hello'} 是一回事。
{'This' 'is' 'a';'two' 'row' 'cell'} 是一个 2×3 元胞数组。分号结束第一行。{1 {2 3} 4} 是一个 3 元素元胞数组,其中元素 2 本身就是一个元胞数组。Braces are also used for content addressing of cell arrays. They act similar to parentheses in this case except that the contents of the cell are returned. Some examples: X{3} is the contents of the third element of X. X{3}(4,5) is the (4,5) element of those contents. X{[1 2 3]} is a comma-separated list of the first three elements of X. It is the same as X{1},X{2},X{3} and makes sense inside [] ,{}, or in function input or output lists (see LISTS). You can repeat the content addressing for nested cells so that X{1}{2} is the contents of the second element of the cell inside the first cell of X. This also works for nested structures, as in X(2).field(3).name or combinations of cell arrays and structures, as in Z{2}.type(3).
那是一个元胞数组。除非你真的需要它们,否则请避免使用它们,因为它们很难使用,它们速度慢得多,而且语法是一种可怕的、不一致的、固定的组合。