﻿ MATLAB中的单元格和数组的连接和索引有何不同？ - 代码日志

#### MATLAB中的单元格和数组的连接和索引有何不同？

>数组可以动态调整自己的内存以允许动态数量的元素,而单元格似乎不会以相同的方式运行：

``````a=[]; a=[a 1]; b={}; b={b 1};
``````

>可以从单元格中检索多个元素,但它们似乎不是来自数组：

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

Cell arrays可能有点棘手,因为你可以在creating,concatenatingindexing中以各种方式使用[],()和{}语法,尽管它们各自做不同的事情.解决你的两点：

>要生成单元格数组,可以使用以下语法之一：

``````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 ()
``````

>使用()索引单元格数组时,它将返回单元格数组中的单元格子集.使用{}索引单元格数组时,它将返回单元格内容的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]
``````