计算嵌套循环中的单个迭代?

时间:2015-07-07 19:58:37

标签: matlab for-loop cell nested-loops cells

我有以下问题。我初始化了一个包含20个单元格的变量,每个单元格都包含一个矩阵。我的矩阵的生成是通过嵌套for循环完成的,所以我有:

matrices = cell(1,20);       

for 1:4
    for 1:5

       *do stuff to get matrix* 

   end
end

我希望能够将第n个结果保存在我的单元格中...例如

对于外环1,内环1 --->细胞的第一个元素

对于外环1,内环2 --->细胞的第二个元素

等等

我知道这将涉及合并

 matrices{counter} = result;

我的循环中的某个地方,但我不知道在哪里包含它以及如何启动计数器。我不能拥有

for 1:20 

在我的循环开始时,因为它会在20次不同的时间执行相同的任务而不能保存正确的结果。

1 个答案:

答案 0 :(得分:2)

您可以在外部循环之外使用counter,也可以在每次迭代时计算current_index

matrices = cell(1,20);  
counter = 1;
for k=1:4
    for j=1:5

       matrices{counter} = zeros(k,j);

       disp(counter);
       counter = counter+1;

       current_index = (k-1)*5+j;
       disp(current_index);

   end
end
相关问题