我应该在matlab中使用什么来收集不同的对象?

时间:2010-11-09 22:46:33

标签: arrays matlab multidimensional-array nested-sets

这在Matlab中是非法的

a = [[1];[2 3]]

在允许这种情况的语言中,这称为嵌套数组。

我在Matlab中找到了一种相同的方法:

 a = {[1];[2 3]}

这叫什么? 如何使用固定大小(比如100)初始化这样的变量而不必编写太多代码?

3 个答案:

答案 0 :(得分:4)

它被称为单元阵列。

使用命令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]);

答案 1 :(得分:2)

或者,我可以通过输入

来发现大括号的含义
help paren

哪个输出:

  

{}大括号用于形成单元格数组。它们类似于         括号[]除了保留嵌套级别。         {magic(3)6.9'hello'}是一个包含三个元素的单元格数组。         {magic(3),6.9,'hello'}是一回事         {'这''是'''';''''''''''''''''''''''''''''''''''''''''         分号结束第一行。 {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).

答案 2 :(得分:0)

那是cell array。除非你真的需要它们,否则要避免使用它们,因为它们使用起来很痛苦,速度要慢得多,并且语法是一种可怕的,不一致的,固定不动的kludge。