How do concatenation and indexing differ for cells and arrays in MATLAB?

ⅰ亾dé卋堺 提交于 2019-11-29 07:57:16

Cell arrays can be a little tricky since you can use the [], (), and {} syntaxes in various ways for creating, concatenating, and indexing them, although they each do different things. Addressing your two points:

  1. To grow a cell array, you can use one of the following syntaxes:

    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. When you index a cell array with (), it returns a subset of cells in a cell array. When you index a cell array with {}, it returns a comma-separated list of the cell contents. For example:

    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]
    

    For d, the {} syntax extracts the contents of cells 2, 3, and 4 as a comma-separated list, then uses [] to collect these values into a numeric array. Therefore, b{2:4} is equivalent to writing b{2}, b{3}, b{4}, or 2, 3, 4.

    With respect to your call to legend, the syntax legend(a{1:2}) is equivalent to legend(a{1}, a{2}), or legend('1', '2'). Thus two arguments (two separate characters) are passed to legend. The syntax legend(b(1:2)) passes a single argument, which is a 1-by-2 string '12'.

Mikhail

Every cell array is an array! From this answer:

[] is an array-related operator. An array can be of any type - array of numbers, char array (string), struct array or cell array. All elements in an array must be of the same type!

Example: [1,2,3,4]

{} is a type. Imagine you want to put items of different type into an array - a number and a string. This is possible with a trick - first put each item into a container {} and then make an array with these containers - cell array.

Example: [{1},{'Hallo'}] with shorthand notation {1, 'Hallo'}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!