Matlab:在矩阵中存储数组?

时间:2014-11-10 15:21:17

标签: matlab

我有很多数组(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 但这是存储矩阵到数组,而不是其他。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

如果向量长度不同,Ying Xiong的建议就是你想要的。但假设元素的数量是常数(它们似乎是),您也可以使用三维数组,其中每个(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等功能。

请注意,您可以对循环进行矢量化,但不知道具体细节,这是不可能知道的。

相关问题