【问题标题】:Declaring a multidimensional array in a single statement在单个语句中声明多维数组
【发布时间】:2011-07-18 07:54:33
【问题描述】:

假设我想创建一个矩阵 A,其尺寸为 3×4×4,使用单个语句(一个相等,没有任何连接),如下所示:

%// This is one continuous row
A = [ [ [3 3 4 4], [8 11 8 7], [4 4 6 7], [4 7 6 6] ];  ...
      [ [3 2 4 2], [9 6 4 12], [4 3 3 4], [5 10 7 3] ]; ...
      [ [2 2 1 2], [3 3 3 2], [2 2 2 2],  [3 3 3 3] ] ]

【问题讨论】:

    标签: matlab multidimensional-array matrix


    【解决方案1】:

    您可以使用cat 沿第三维“分层”二维矩阵,例如:

    A = cat(3, ones(4), 2*ones(4), 3*ones(4));
    

    从技术上讲,这是串联,但它仍然只是一个分配。

    【讨论】:

      【解决方案2】:

      concatenation operator [] 仅适用于二维,例如[a b] 用于水平连接或[a; b] 用于垂直连接。要创建matrices with higher dimensions,您可以使用reshape 函数,或者初始化您想要的大小的矩阵,然后用您的值填充它。例如,您可以这样做:

      A = reshape([...], [3 4 4]);  % Where "..." is what you have above
      

      或者这个:

      A = zeros(3, 4, 4);  % Preallocate the matrix
      A(:) = [...];        % Where "..." is what you have above
      

      【讨论】:

      • 第二个是我做的。非常感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多