【问题标题】:Get the iteration number inside a MATLAB for loop获取 MATLAB for 循环中的迭代次数
【发布时间】:2014-03-10 05:42:14
【问题描述】:

假设我在 MATLAB 中有一个 for 循环:

scales = 5:5:95;
for scale = scales
    do stuff
end

如何尽可能简洁地获取 MATLAB for 循环中的迭代次数?

以 Python 为例,我会使用:

for idx, item in enumerate(scales):

其中 idx 是迭代次数。

我知道在 MATLAB 中(就像在任何其他语言中一样)我可以创建一个计数变量:

scales = 5:5:95;
scale_count = 0;
for scale = scales
    scale_count = scale_count + 1;
    do stuff
end

否则我可以使用find

scales = 5:5:95;
for scale = scales
    scale_count = find(scales == scale);
    do stuff
end

但我很想知道是否存在更简洁的方法来做到这一点,例如就像在 Python 示例中一样。

【问题讨论】:

  • 循环计数是什么意思?那不就是scale吗?还是您在寻找其他东西?
  • 我的意思是迭代次数。例如。在第 1 次迭代时 scale == 5;在第 2 次迭代时 scale == 10;等等
  • 啊。我认为最好的方法就是声明一个变量; AFAIK 没有更清洁的方法。

标签: matlab


【解决方案1】:

也许您可以使用以下内容:

scales = 5:5:95;
for iter = 1:length(scales)
    scale=scales(iter); % "iter" is the iteration number.
    do stuff
end

【讨论】:

  • 是的,谢谢,这是另一种常见的解决方案,但仍然不是更简洁:(
【解决方案2】:

由于for 会遍历你给它的任何列,另一种逼近多个循环变量的方法是使用适当构造的矩阵:

for scale=[5:5:95; 1:19]
    % do stuff with scale(1) or scale(2) as appropriate
end

(我个人的偏好是根据 Parag 的回答循环遍历索引,并直接在循环内引用 data(index),无需中间。Matlab 的语法在最好的时候不是很简洁 - 你只是习惯了给它)

【讨论】:

    【解决方案3】:

    MATLAB 的方式可能是用向量来做的。

    例如,假设您想在向量中查找是否存在与其位置相等的值。你通常会这样做:

    a = [10 20 1 3 5];
    found = 0;
    for index = 1:length(a)
        if a(index) == index
            found = 1;
            break;
        end
    end
    

    您可以这样做:

    found = any(a == 1:length(a));
    

    一般

    for i=1:length(a)
        dostuff(a(i), i);
    end
    

    可以替换为:

    dostuff(a(i), 1:length(a))
    

    它可以被矢量化或

    arrayfun(@dostuff, a, 1:length(a))
    

    否则。

    【讨论】:

    • 当然你可以用你自己的范围替换 1:length(a),例如5:5:95 或其他任何时间
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    • 2019-12-08
    • 2012-10-27
    • 2012-08-07
    • 2014-08-24
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多