【问题标题】:Matlab: store array in matrix?Matlab:将数组存储在矩阵中?
【发布时间】:2014-11-10 15:21:16
【问题描述】:

我有很多数组(n*1 维度),我该怎么做

matrix = [];
for i = 1:5
  for j =1:5
    matrix (i,j) = zeros(n,1); % store a given array to a cell of a matrix 
  end
end

我找到Array of Matrices in MATLAB 但这是将矩阵存储到数组中,而不是其他情况。

【问题讨论】:

  • n 在迭代之间是否发生变化?
  • @kkuilla 好吧...我想知道这两种情况(改变和不改变)。

标签: matlab


【解决方案1】:

如果向量的长度不同,Ying Xiong 的建议就是你想要的。但是假设元素的数量是恒定的(它们似乎是),您也可以使用一个 3 维数组,其中每个 (i,j) 元素包含一个三维向量,如下所示:

rows = 5; cols = 5; n = 10;     %// Dimensions
matrix = zeros(rows, cols, n);  %// Initialize matrix
vector = 1:n;                   %// Just an example    
for ii = 1:rows                 %// Bad practice to use i as a variable name 
   for jj = 1:cols              %// Bad practice to use j as a variable name
      matrix(ii,jj,:) = vector; %// Assignment
   end
end

现在每个索引(i,j) 都包含您想要的向量,例如:

squeeze(matrix(1,1,:))
ans =
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10

如果您想对所有元素执行类似的操作,将所有值放在一个矩阵中可能是一件好事,因为向量化方法在 MATLAB 中通常非常快。您可能想查看permutereshapebsxfun 等函数。

请注意,您也许可以对循环进行矢量化处理,但在不了解具体细节的情况下,这是不可能知道的。

【讨论】:

    【解决方案2】:

    您需要使用cell array

    n = 10;
    matrix = cell(5,5);
    for i = 1:5
      for j = 1:5
        matrix{i,j} = zeros(n,1);
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2021-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2020-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多