开发者

What should I use for a collection of different objects in matlab?

This is illegal in Matlab

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

In languages that allow this, this is called nested arrays.

I found a way of doing the same in Matlab:

 a = {[1];[2 3]开发者_JAVA技巧}

What is this called? How initialize such a variable with a fixed size (say 100) without having to write much code?


It is called a cell array.

You initialize it using the command cell

cellArray = cell(3,2); %# this makes a 3-by-2 cell array

An alternative way to store collections of different objects is the struct, which you'd initialize like this

myStruct = struct('firstField',1,'secondField',[2 3])

The advantage of structs over cells is that the fields are named, which makes it a lot easier to deal with and document. Cells can be very convenient for storing data if you want to manipulate the data often, because you can for example use cellfun with them. I find myself often using cells to keep data inside a function, but using structures (or objects) to pass data between functions.

Also, if you have a list of numbers and want to distribute them to elements of the cell array, you can use num2cell, which puts every element of the array separately into an element of the cell array, or mat2cell, in case you want to split the array unevenly.

a = {1,[2 3]}

is equivalent to

b = mat2cell([1 2 3],[1 1],[1 2]);


Alternatively I could discover the meaning of the curly brackets by typing

help paren

Which outputs:

{ } Braces are used to form cell arrays. They are similar to brackets [ ] except that nesting levels are preserved. {magic(3) 6.9 'hello'} is a cell array with three elements. {magic(3),6.9,'hello'} is the same thing.
{'This' 'is' 'a';'two' 'row' 'cell'} is a 2-by-3 cell array. The semicolon ends the first row. {1 {2 3} 4} is a 3 element cell array where element 2 is itself a cell array.

 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).


That's a cell array. Avoid them unless you really need them, because they're a pain to work with, they're much slower, and the syntax is a horrible, inconsistent, bolt-on kludge.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜