【问题标题】:How do concatenation and indexing differ for cells and arrays in MATLAB?MATLAB 中的单元格和数组的连接和索引有何不同?
【发布时间】:2011-02-09 09:58:44
【问题描述】:

我对 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.
    

这些是正确的吗?单元格和数组还有哪些不同的用法?

【问题讨论】:

    标签: arrays matlab indexing cell concatenation


    【解决方案1】:

    Cell arrays 可能有点棘手,因为您可以以各种方式使用 []() {} 语法来处理 creatingconcatenating 和 @ 987654324@他们,尽管他们各自做不同的事情。解决你的两点:

    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'

    【讨论】:

      【解决方案2】:

      每个元胞数组都是一个数组! From this answer:

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

      示例:[1,2,3,4]

      {} 是一种类型。想象一下,您想将不同类型的项目放入一个数组中——一个数字和一个字符串。这可以通过一个技巧来实现 - 首先将每个项目放入容器 {} 中,然后使用这些容器创建一个数组 - 元胞数组。

      示例:[{1},{'Hallo'}] 带有速记符号{1, 'Hallo'}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-16
        • 1970-01-01
        • 1970-01-01
        • 2018-08-23
        • 2013-01-27
        • 2014-02-16
        • 1970-01-01
        • 2012-10-12
        相关资源
        最近更新 更多