【问题标题】:Counting individual iterations in a nested loop?计算嵌套循环中的单个迭代?
【发布时间】:2015-09-25 12:10:39
【问题描述】:

我有以下问题。我已经初始化了一个包含 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 次不同的时间并且不会保存正确的结果。

【问题讨论】:

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


    【解决方案1】:

    您可以在外循环之外使用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
    

    【讨论】:

    • 如果你在循环外定义kj的长度,你可以使用sub2ind优雅地获取索引。
    猜你喜欢
    • 2016-05-20
    • 2013-05-09
    • 2014-10-22
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    相关资源
    最近更新 更多