2010-04-18 56 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'}