2010-04-18 55 views
4

我对MATLAB中使用单元和数组有点困惑,希望对几点做一些说明。这里是我的意见:在MATLAB中单元和数组的连接和索引有何不同?

  1. 数组可以动态地调整自己的内存,允许元素的动态数量,同时细胞似乎不以同样的方式行事:

    a=[]; a=[a 1]; b={}; b={b 1}; 
    
  2. 几个要素可从细胞中提取,但它似乎并不像他们可以从阵列:

    a={'1' '2'}; figure; plot(...); hold on; plot(...); legend(a{1:2}); 
    b=['1' '2']; figure; plot(...); hold on; plot(...); legend(b(1:2)); 
    %# b(1:2) is an array, not its elements, so it is wrong with legend. 
    

这些是正确的吗?单元格和数组之间有什么其他不同的用法?

回答

12

Cell arrays可有点棘手,因为你可以用各种方式[](){}语法为creatingconcatenatingindexing他们,虽然他们各自做不同的事情。解决您的两点:

  1. 长出单元阵列,您可以使用以下语法之一:

    b = [b {1}];  % Make a cell with 1 in it, and append it to the existing 
           % cell array b using [] 
    b = {b{:} 1}; % Get the contents of the cell array as a comma-separated 
           % list, then regroup them into a cell array along with a 
           % new value 1 
    b{end+1} = 1; % Append a new cell to the end of b using {} 
    b(end+1) = {1}; % Append a new cell to the end of b using() 
    
  2. 当指数与()单元阵列,它返回小区的子集在单元阵列中。当您使用{}索引单元阵列时,它会返回单元格内容的comma-separated list。例如:

    b = {1 2 3 4 5}; % A 1-by-5 cell array 
    c = b(2:4);  % A 1-by-3 cell array, equivalent to {2 3 4} 
    d = [b{2:4}];  % A 1-by-3 numeric array, equivalent to [2 3 4] 
    

    d,所述{}语法提取单元2,3的内容,和4作为comma-separated list,然后使用[]收集这些值插入数字数组。因此,b{2:4}相当于编写了b{2}, b{3}, b{4}2, 3, 4

    对于您致电legend,语法legend(a{1:2})相当于legend(a{1}, a{2})legend('1', '2')。因此两个自变量(两个单独的字符)被传递给legend。语法legend(b(1:2))传递一个单参数,它是一个1乘2的字符串'12'

4

每个单元格数组都是一个数组! From this answer

[]是一个数组相关的运算符。数组可以是任何类型 - 数组数组,char数组(字符串),结构数组或单元数组。数组中的所有元素必须是相同类型的

实施例:[1,2,3,4]

{}是一种类型。想象一下,你想把不同类型的项目放到一个数组中 - 一个数字和一个字符串。这是可能的一个技巧 - 首先将每个项目放入一个容器{},然后用这些容器(单元阵列)制作一个数组。

例如:[{1},{'Hallo'}]用简写符号{1, 'Hallo'}